13.1 make a duplicate of an existing file

import os
import shutil
from zipfile import ZipFile
from os import path
 
def main():
 
    # make a duplicate of an existing file
    if path.exists("textfile.txt"):
        # get the path to the file in the current directory
        src = path.realpath("textfile.txt")
 
if __name__ == "__main__":
    main()

13.2 separate the path part from the filename

import os
import shutil
from zipfile import ZipFile
from os import path
 
def main():
 
    # make a duplicate of an existing file
    if path.exists("textfile.txt"):
        # get the path to the file in the current directory
        src = path.realpath("textfile.txt")
 
    # separate the path part from the filename
    head, tail = path.split(src)
    print "path: " + head
    print "file: " + tail
 
if __name__ == "__main__":
    main()

13.3 make a backup copy of a file

The shutil module offers a number of high-level operations on files and collections of files. In particular, functions are provided which support file copying and removal. For operations on individual files, see also the os module.

import os
import shutil
from zipfile import ZipFile
from os import path
 
def main():
 
    # make a duplicate of an existing file
    if path.exists("textfile.txt"):
        # get the path to the file in the current directory
        src = path.realpath("textfile.txt")
 
    # let's make a backup copy by appending "bak" to the name
    dst = src + ".bak"
    # now use the shell to make a copy of the file
    shutil.copy(src, dst)
 
if __name__ == "__main__":
    main()

13.4 copy over the permissions, etc.

The shutil.copy(src, dst) method only copies over the contents of a file (see docs above.)

To copy over permissions etc. you need to also use shutil.copystat(src, dst).

import os
import shutil
from zipfile import ZipFile
from os import path
 
def main():
 
    # make a duplicate of an existing file
    if path.exists("textfile.txt"):
        # get the path to the file in the current directory
        src = path.realpath("textfile.txt")
 
    # copy over the permissions, modification times, and other info
    shutil.copystat(src, dst)
 
if __name__ == "__main__":
    main()

13.5 rename the original file

For operations on individual files, see the os module.

import os
import shutil
from zipfile import ZipFile
from os import path
 
def main():
 
    # rename the original file
    os.rename("textfile.txt", "newfile.txt")
 
if __name__ == "__main__":
    main()

13.6 put things into a ZIP archive

Using the shutil.make_archive("archive", "zip", root_dir) method.

import os
import shutil
from zipfile import ZipFile
from os import path
 
def main():
 
    # now put things into a ZIP archive
    root_dir, tail = path.split(src)
    shutil.make_archive("archive", "zip", root_dir)
 
if __name__ == "__main__":
    main()

This archives all the contents of root_dir variable. If you want to archive a file and not a directory you need more control and that is offered by: zipfile.

13.7 more control over ZIP files

See Zipfile Module docs. The ZIP file format is a common archive and compression standard. This module provides tools to create, read, write, append, and list a ZIP file. Any advanced use of this module will require an understanding of the format, as defined in PKZIP Application Note.

This module does not currently handle multi-disk ZIP files. It can handle ZIP files that use the ZIP64 extensions (that is ZIP files that are more than 4 GByte in size). It supports decryption of encrypted files in ZIP archives, but it currently cannot create an encrypted file. Decryption is extremely slow as it is implemented in native Python rather than C.

import os
import shutil
from zipfile import ZipFile
from os import path
 
def main():
 
    # more fine-grained control over ZIP files
    with ZipFile("testzip.zip", "w") as newzip:
        newzip.write("newfile.txt")
        newzip.write("textfile.txt.bak")
 
if __name__ == "__main__":
    main()

n.b. with is a Python construct that creates its own local scope, so when you say as newzip with makes newzip available to its own local scope. Any statements indented below with have access to that variable.

Its not necessary to run .close() on newzip because when the flow of the program falls outside of the scope of with the file will be cleaned up and closed automatically, its just something Python does when you scope blocks of code like this.

Now we have zipped a single file.

13.8 Entire script

import os
import shutil
from zipfile import ZipFile
from os import path
 
def main():
 
    # make a duplicate of an existing file
    if path.exists("textfile.txt"):
        # get the path to the file in the current directory
        src = path.realpath("textfile.txt")
 
    # separate the path part from the filename
    head, tail = path.split(src)
    print "path: " + head
    print "file: " + tail
 
    # let's make a backup copy by appending "bak" to the name
    dst = src + ".bak"
    # now use the shell to make a copy of the file
    shutil.copy(src, dst)
 
    # copy over the permissions, modification times, and other info
    shutil.copystat(src, dst)
 
    # rename the original file
    os.rename("textfile.txt", "newfile.txt")
 
    # now put things into a ZIP archive
    root_dir, tail = path.split(src)
    shutil.make_archive("archive", "zip", root_dir)
 
    # more fine-grained control over ZIP files
    with ZipFile("testzip.zip", "w") as newzip:
        newzip.write("newfile.txt")
        newzip.write("textfile.txt.bak")
 
if __name__ == "__main__":
    main()