Adding Files to a ZIP File


tFile = zipfile.ZipFile("files.zip", 'w') files = os.listdir(".") for f in files:     tFile.write(f)

The zipfile module, included with Python, provides a set of easy-to-use methods to create and manipulate ZIP files. The ZipFile(filename [, mode [, compression]]) method creates or opens a ZIP file depending on the mode specified. The available modes for ZIP files are r, w, and a to read, write, or append, respectively. Using the w mode will create a new ZIP file or truncate the existing file to zero if it already exists.

The optional compression argument will accept either the ZIP_STORED(not compressed) or ZIP_DEFLATED(compressed) compression options to set the default compression when writing files to the archive.

Once the ZIP file has been opened in write mode, files can be added to it using the write(filename [,arcname [, compression]]) method. The write method adds the file specified in filename to the archive. The optional arcname argument enables you to specify what name the file should have inside the archive.

import os import zipfile #Create the zip file tFile = zipfile.ZipFile("files.zip", 'w') #Write directory contents to the zip file files = os.listdir(".") for f in files:     tFile.write(f) #List archived files for f in tFile.namelist():     print "Added %s" % f tFile.close()


add_zip.py

Added add_zip.py Added del_tree.py Added dir_tree.py Added extract.txt Added extract_tar.py Added files.zip Added file_lines.py Added find_file.py Added get_zip.py Added input.txt Added open_file.py Added output.old Added read_file.py Added read_line.py Added read_words.py Added ren_file.py Added tar_file.py Added write_file.py


Output from add_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