Retrieving Files from a ZIP File


tFile = zipfile.ZipFile("files.zip", 'r') buffer = tFile.read("ren_file.py")

Retrieving file contents from a ZIP file is easily done using the read(filename) method included in the zipfile module. Once the ZIP file is opened in read mode, the read method is called and the contents of the specified file are returned as a string. Once the contents are returned, they can be added to a list or dictionary, printed to the screen, written to a file, or any number of other possibilities.

The example in get_zip.py opens the ZIP file created in the previous phrase, reads Python file ren_file.py, prints the contents to the screen, and then writes the contents to a new file called extract.txt.

import os import zipfile tFile = zipfile.ZipFile("files.zip", 'r') #List info for archived file print tFile.getinfo("input.txt") #Read zipped file into a buffer buffer = tFile.read("ren_file.py") print buffer #Write zipped file contents to new file f = open("extract.txt", "w") f.write(buffer) f.close() tFile.close()


get_zip.py

<zipfile.ZipInfo instance at 0x008DCB70> import os oldFileName = "/books/python/CH4/code/output.txt" newFileName = "/books/python/CH4/code/output.old" #Old Listing for file in os.listdir("/books/python/CH4/code/"):     if file.startswith("output"):         print file #Remove file if the new name already exists if os.access(newFileName, os.X_OK):     print "Removing " + newFileName     os.remove(newFileName) #Rename the file os.rename(oldFileName, newFileName) #New Listing for file in os.listdir("/books/python/CH4/code/"):     if file.startswith("output"):         print file


Output from get_zip.py code




Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net