Module 4
Module 4
example.zip
Reading ZIP Files
• To read the contents of a ZIP file, first you must create
a ZipFile object.
• ZipFile objects are conceptually similar to the File
objects.
• They are values through which the program interacts
with the file.
• To create a ZipFile object, call the zipfile.ZipFile()
function, passing it a string of the .zip file’s filename.
• Note that zipfile is the name of the Python module,
and ZipFile() is the name of the function.
>>> import zipfile, os
>>> os.chdir('C:\\') # move to the folder with example.zip
>>> exampleZip = zipfile.ZipFile('example.zip')
>>> exampleZip.namelist()
• ['spam.txt', 'cats/', 'cats/catnames.txt', 'cats/zophie.jpg']
>>> spamInfo = exampleZip.getinfo('spam.txt')
>>> spamInfo.file_size
• 13908
>>> spamInfo.compress_size
• 3828
>>> 'Compressed file is %sx smaller!' %
(round(spamInfo.file_size / spamInfo.compress_size, 2))
• 'Compressed file is 3.63x smaller!'
• >>> exampleZip.close()
Contd..
• A ZipFile object has a namelist() method that returns a list
of strings for all the files and folders contained in the ZIP
file.
• These strings can be passed to the getinfo() ZipFile method
to return a ZipInfo object about that particular file.
• ZipInfo objects have their own attributes, such as file_size
and compress_size in bytes, which hold integers of the
original file size and compressed file size, respectively.
• While a ZipFile object represents an entire archive file, a
ZipInfo object holds useful information about a single file in
the archive.
Extracting from ZIP Files
• The extractall() method for ZipFile objects
extracts all the files and folders from a ZIP file
into the current working directory.
>>> import zipfile, os
>>> os.chdir('C:\\') # move to the folder with example.zip
>>> exampleZip = zipfile.ZipFile('example.zip')
>>> exampleZip.extractall()
>>> exampleZip.close()
Contd..
• The extract() method for ZipFile objects will
extract a single file from the ZIP file.
>>> exampleZip.extract('spam.txt')
• 'C:\\spam.txt'
>>>exampleZip.extract('spam.txt','C:\\some\\new\\
folders')
• 'C:\\some\\new\\folders\\spam.txt'
>>> exampleZip.close()
Creating and Adding to ZIP Files
• To create your own compressed ZIP files, you
must open the ZipFile object in write mode by
passing 'w' as the second argument.
Contd..
• When you pass a path to the write() method
of a ZipFile object, Python will compress the
file at that path and add it into the ZIP file.
• The write() method’s first argument is a string
of the filename to add.
• The second argument is the compression type
parameter, which tells the computer what
algorithm it should use to compress the files.
• Set this value to zipfile.ZIP_DEFLATED.
Contd..
>>> import zipfile
>>> newZip = zipfile.ZipFile('new.zip', 'w')
>>>newZip.write('spam.txt',compress_type=zipfile.ZIP
_DEFLATED)
>>> newZip.close()
Project: Backing Up a Folder into a ZIP File