| 10 | from zipfile import ZipFile |
| 11 | |
| 12 | def main(): |
| 13 | # make a duplicate of an existing file |
| 14 | if path.exists("textfile.txt"): |
| 15 | # get the path to the file in the current directory |
| 16 | src = path.realpath("textfile.txt"); |
| 17 | |
| 18 | # let's make a backup copy by appending "bak" to the name |
| 19 | dst = src + ".bak" |
| 20 | # now use the shell to make a copy of the file |
| 21 | shutil.copy(src,dst) |
| 22 | |
| 23 | # rename the original file |
| 24 | os.rename("textfile.txt", "newfile.txt") |
| 25 | |
| 26 | # now put things into a ZIP archive |
| 27 | root_dir,tail = path.split(src) |
| 28 | shutil.make_archive("archive", "zip", root_dir) |
| 29 | |
| 30 | # more fine-grained control over ZIP files |
| 31 | with ZipFile("testzip.zip","w") as newzip: |
| 32 | newzip.write("newfile.txt") |
| 33 | newzip.write("textfile.txt.bak") |
| 34 | |
| 35 | if __name__ == "__main__": |
| 36 | main() |