Archives in Python

The Zip file is the most popular file format used for file compression. It is the old technique but still in use since DOS operating systems.

Python is provides Module in zipfile to complete access over the zip file.

Zipfile() :

This function returns the zip objects, the file parameter should be string for creating, reading and loading the zip file. We will use open() function along with their suitable mode to create the zip file

Here is the some parameter of the zipfile() method.

write()

Let’s create the zipfile compression file.

import zipfile
newzipfile=zipfile.ZipFile('salesforce.zip','w')
newzipfile.write('abc.txt')
newzipfile.close()

read()

You can read the data simple using read() method

import zipfile
newzipfile=zipfile.ZipFile("test.zip","r")
data=newzip.read('abc.txt')
print(data)

Output

b'making txt file'

printdir()

This method is used for see the list in zip file

import zipfile
newzip=zipfile.ZipFile("test.zip","r")
print(newzip.printdir())

Output

C:\Users\ASUS\Desktop>python exm.py
File Name                                             Modified             Size
abc.txt                                        2020-09-07 18:38:02           15
None

C:\Users\ASUS\Desktop>

extract()

This method is used for extracting the file from the zip

import zipfile
newzip=zipfile.ZipFile("test.zip","r")
newzip.extract('abc.txt')

extractall()

This method is used for extract all the file from the zip

import zipfile
newzip=zipfile.ZipFile("test.zip","r")
newzip.extractall('C:\\Users\\ASUS\\Desktop’)   #this is optional to give path

getinfo()

This method is related to the file information.

import zipfile
newzip=zipfile.ZipFile("test.zip","r")
info=newzip.getinfo('abc.txt')
print(info.filename,info.file_size,info.date_time)

Output

C:\Users\ASUS\Desktop>python exm.py
abc.txt 15 (2020, 9, 7, 18, 38, 2)

setpassword()

This method is used to make file write protected.

import zipfile
newzipfile=zipfile.ZipFile('test1.zip','w')
newzipfile.setpassword(b'1234')
newzipfile.write('abc.txt')
newzipfile.close()
Subscribe Now