0% found this document useful (0 votes)
3 views27 pages

Python zipfile Module Guide

Uploaded by

Sneha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views27 pages

Python zipfile Module Guide

Uploaded by

Sneha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Compressing Files with the zipfile Module

ZIP is one of the most popular file formats used for archiving and compression. It has been in
use since the days of MSDOS and PC and has been used by famous PKZIP application.

Python's standard library provides zipfile module with classes that facilitate the tools for
creating, extracting, reading and writing to ZIP archives.

ZipFile() function

This function returns a ZipFile object from a file parameter which can be a string or file object as
created by built-in open() function. The function needs a mode parameter whose default value is
'r' although it can take 'w' or 'a' value for opening the archive in read, write or append mode
respectively.

The archive by default is uncompressed. To specify the type of compression algorithm to be


used, one of the constants has to be assigned to compression parameter.

zipfile.ZIP_STORED for an uncompressed archive member.

for the usual ZIP compression method. This


zipfile.ZIP_DEFLATED
requires the zlib module.

for the BZIP2 compression method. This requires


zipfile.ZIP_BZIP2
the bz2 module.

for the LZMA compression method. This requires


zipfile.ZIP_LZMA
the lzma module.

The ZipFile object uses following methods −

write() method

This method adds the given file to the ZipFile object.

import zipfile
newzip=[Link]('[Link]','w')
[Link]('[Link]')
[Link]()

This creates [Link] file in th current directory. Additional file can be added to already
existing archive by opening it in append mode ('a' as the mode).
import zipfile
newzip=[Link]('[Link]','a')
[Link]('[Link]')
[Link]()

read() method

This method reads data from a particular file in the archive.

import zipfile
newzip=[Link]('[Link]','r')
data = [Link]('[Link]')
print (data)
[Link]()

Output

b'["Rakesh", {"marks": [50, 60, 70]}]'

printdir() method

This method lists all file in given archive.

import zipfile
newzip=[Link]('[Link]','r')
[Link]()
[Link]()

Output

File Name Modified Size


[Link] 2023-03-30 21:55:48 132
[Link] 2023-04-03 22:01:56 35

extract() method

This method extracts a specified file from archive by default to current directory or to one given
as second parameter to it.

import zipfile
newzip=[Link]('[Link]','r')
[Link]('[Link]', 'newdir')
[Link]()

extractall() method

This method extracts all files in the archive to current directory by default. Specify alternate
directory if required as parameter.

import zipfile
newzip=[Link]('[Link]','r')
[Link]('newdir')
[Link]()

getinfo() method

This method returns ZipInfo object corresponding to the given file. The ZipInfo object contains
different metadata information of the file.

Following code obtains ZipInfo object of '[Link]' from the archive and retrieves filename, size
and date-time information from it.

import zipfile
newzip=[Link]('[Link]','r')
info = [Link]('[Link]')
print ([Link], info.file_size, info.date_time)
[Link]()

Output

[Link] 132 (2023, 3, 30, 21, 55, 48)

infolist() method

import zipfile
newzip=[Link]('[Link]','r')
info = [Link]()
print (info)
[Link]()

Output
[<ZipInfo filename='[Link]' filemode='-rw-rw-rw-' file_size=132>,
<ZipInfo filename='[Link]' filemode='-rw-rw-rw-' file_size=35>]

namelist() method

This method of ZipFile object returns a list of all files in the archive.

import zipfile
newzip=[Link]('[Link]','r')
info = [Link]()
print (info)
[Link]()

Output

['[Link]', '[Link]']

setpassword() method

This method sets password parameter which must be provided at the time of extracting the
archive.

pprint module (Data pretty printer)

The pprint module (lib/[Link]) is a part of Python’s standard library which is distributed along
with standard Python distribution. The name pprint stands for pretty printer. The pprint module’s
functionality enables aesthetically good looking appearance of Python data structures. Any data
structure that can be correctly parsed by Python interpreter is elegantly formatted. The formatted
expression is kept in one line as far as possible, but breaks into multiple lines if the length
exceeds the width parameter of formatting. One unique feature of pprint output is that the
dictionaries are automatically sorted before the display representation is formatted.

The pprint module contains definition of PrettyPrinter class. Its constructor takes following
format −

[Link](indent, width, depth, stream, compact)


The indent parameter defines indentation added on each recursive level. Default is 1.

The width parameter by default is 80. Desired output is restricted by this value. If the length is
greater than width, it is broken in multiple lines.

The depth parameter controls number of levels to be printed.

The stream parameter is by default [Link] – the default output device. It can take any stream
object such as file.

The compact parameter id set to False by default. If true, only the data adjustable within width
will be displayed.

The PrettyPrinter class defines following methods −

pprint() − prints the formatted representation of PrettyPrinter object

pformat() − Returns the formatted representation of object, based on parameters to the


constructor.

Following example demonstrates simple use of PrettyPrinter class.

import pprint
students = {"Dilip":["English", "Maths", "Science"],
"Raju":{"English":50,"Maths":60, "Science":70},
"Kalpana":(50,60,70)}
pp = [Link]()
print ("normal print output")
print (students)
print ("----")
print ("pprint output")
[Link](students)

The output shows normal as well as pretty print display.

normal print output


{'Dilip': ['English', 'Maths', 'Science'], 'Raju': {'English': 50, 'Maths': 60, 'Science': 70}, 'Kalpana':
(50, 60, 70)}
----
pprint output
{'Dilip': ['English', 'Maths', 'Science'],
'Kalpana': (50, 60, 70),
'Raju': {'English': 50, 'Maths': 60, 'Science': 70}}

The pprint module also defines convenience functions pprint() and pformat() corresponding to
PrettyPrinter methods. The example below uses pprint() function.

from pprint import pprint


students = {"Dilip":["English", "Maths", "Science"],
"Raju":{"English":50,"Maths":60, "Science":70},
"Kalpana":(50,60,70)}
print ("normal print output")
print (students)
print ("----")
print ("pprint output")
pprint (students)

Next example uses pformat() method as well as pformat() function. To use pformat() method,
PrettyPrinter object is first set up. In both cases, the formatted representation is displayed using
normal print() function.

import pprint
students = {"Dilip":["English", "Maths", "Science"],
"Raju":{"English":50,"Maths":60, "Science":70},
"Kalpana":(50,60,70)}
print ("using pformat method")
pp = [Link]()
string = [Link](students)
print (string)
print ('------')
print ("using pformat function")
string = [Link](students)
print (string)

Here is the output of above code

using pformat method


{'Dilip': ['English', 'Maths', 'Science'],
'Kalpana': (50, 60, 70),
'Raju': {'English': 50, 'Maths': 60, 'Science': 70}}
------
using pformat function
{'Dilip': ['English', 'Maths', 'Science'],
'Kalpana': (50, 60, 70),
'Raju': {'English': 50, 'Maths': 60, 'Science': 70}}

Pretty printer can also be used with custom classes. Inside the class __repr__() method is
overridden. The __repr__() method is called when repr() function is used. It is the official string
representation of Python object. When we use object as parameter to print() function it prints
return value of repr() function.

In following example, the __repr__() method returns the string representation of player object

import pprint
class player:
def __init__(self, name, formats = [], runs = []):
[Link] = name
[Link] = formats
[Link] = runs
def __repr__(self):
dct = {}
dct[[Link]] = dict(zip([Link],[Link]))
return (repr(dct))
l1 = ['Tests','ODI','T20']
l2 = [[140, 45, 39],[15,122,36,67, 100, 49],[78,44, 12, 0, 23, 75]]
p1 = player("virat",l1,l2)
pp = [Link]()
[Link](p1)

The output of above code is −

{'virat': {'Tests': [140, 45, 39], 'ODI': [15, 122, 36, 67, 100, 49], 'T20': [78, 44, 12, 0, 23, 75]}}

Recursive data structure with pprint


When we try to print a recursive object with pprint, only first representation is displayed and for
subsequent recursions, only its reference is printed.

>>> import pprint


>>> numbers = list(range(1,6))
>>> [Link](numbers)
>>> print (numbers)
[1, 2, 3, 4, 5, [...]]
>>> [Link](numbers)
[1, 2, 3, 4, 5, <Recursion on list with id=1403633698824>]

Restricting output width

If width parameter is changed from default 80 to other value, the output is formatted in such a
way that multiple lines are displayed while care is taken not to violate the syntax.

import pprint
students = {"Dilip":["English", "Maths", "Science"],
"Raju":{"English":50,"Maths":60, "Science":70},
"Kalpana":(50,60,70)}
pp=[Link](width = 20)
[Link](students)

The code is similar to first example in this article. However, PrettyPrinter object is constructed
with width parameter as 20. Hence the pprint output is accordingly formatted.

{'Dilip': [ 'English',
'Maths',
'Science'],
'Kalpana': (50,
60,
70),
'Raju': {'English': 50,
'Maths': 60,
'Science': 70}}

Common questions

Powered by AI

The pprint module provides several advantages over the regular print function by making complex Python data structures more readable. It formats the output with proper indentation and line breaks, making it easier to interpret nested collections and large dictionaries. Additionally, it sorts dictionaries by key, which enhances readability. These features are particularly useful for debugging and logging purposes, where quick and clear understanding of the data structure is necessary .

Pprint is advantageous for recursive data structures as it intelligently represents recursions by showing a reference marker instead of endlessly printing the structure, thereby preventing infinite loops and excessive output. However, a limitation of its default settings is that it doesn't fully resolve recursive references, making the output less informative without additional context or tracing, which might require developers to manually interpret recursive relationships within the data structure .

The 'ZipInfo' object in the Python zipfile module holds metadata about a file in a ZIP archive. It can be retrieved using the 'getinfo' method of the ZipFile object, which returns a ZipInfo instance for a specified file. The ZipInfo object contains various details such as file name, file size, and the date and time when the file was last modified, allowing developers to access file metadata efficiently .

Altering the 'width' parameter in the PrettyPrinter class impacts how the output is formatted by controlling the maximum line length before additional line breaks are introduced. With a smaller width value, output spans multiple lines, enhancing readability for lengthy or complex structures. Compactness is compromised to gain clarity, making this parameter critical for customizing display according to specific readability needs .

The 'write' method in the ZipFile class is used to add files to a ZIP archive. When this method is called, it takes the file name as its argument and adds the specified file to the ZIP archive represented by the ZipFile object. This method can be used in both write ('w') and append ('a') modes. In write mode, a new ZIP file is created, and in append mode, files are added to an existing ZIP archive .

The 'setpassword' method in the zipfile module is used to set a password for decrypting files during extraction. To utilize this method, a password needs to be assigned to the ZipFile object before accessing encrypted files. This feature enhances security by restricting file access to authorized users who know the password, suitable for environments where data protection is critical .

The pprint module can handle custom class objects by relying on the __repr__ method of the class. This method is overridden to provide a string representation of the object that pprint will format. For custom classes, defining a comprehensive __repr__ method ensures that pprint can display the object's data clearly and aesthetically. This approach aids in visualizing complex data structures in custom applications .

The 'extractall' method enhances the ZipFile class's functionality by allowing the extraction of all files from a ZIP archive with a single command. This method can extract files to the current directory by default, or to a specified directory, streamlining the extraction process when dealing with multiple files. It simplifies user operations by bypassing the need for iterative file extraction .

Using the LZMA compression method in the zipfile module could be beneficial in scenarios where maximum compression is crucial, despite requiring more computational resources and memory usage. LZMA often achieves higher compression ratios compared to traditional DEFLATED compression, making it suitable for reducing storage space for larger files or when high network transfer efficiency is required. However, the choice depends on the trade-off between compression speed and file size .

In Python's zipfile module, importing additional modules for certain compression methods like BZIP2 and LZMA is mandatory because these methods rely on functionalities provided by respective modules such as 'bz2' for BZIP2 and 'lzma' for LZMA. These modules contain specialized algorithms and implementations that the zipfile module itself does not have, ensuring users benefit from optimized compression routines and interoperability with standard formats .

You might also like