Python Zip | Zipping Files With Python
FREE Online Courses: Your Passport to Excellence - Start Now
Zip is one of the most widely used archive file formats. Since it reconstructs the compressed data perfectly, it supports lossless compression. A zip file can either be a single file or a large directory with multiple files and sub-directories. Its ability to reduce a file size makes it an ideal tool for storing and transferring large-size files. It is most commonly used in sending mails. To make working with zip files feasible and easier, Python contains a module called zipfile. With the help of zipfile, we can open, extract, and modify zip files quickly and simply. let’s learn about Python Zip!!
Viewing the Members of Python Zip File
All files and directories inside a zip file are called members. We can view all the members in a zip file by using the printdir() method. The method also prints the last modified time and the size of each member.
Example of using prindir() method in Python
from zipfile import ZipFile file = "geeks.zip" # zip file name with ZipFile(file, 'r') as zip: zip.printdir()
Output
PythonGeeks.txt 2021-06-28 08:41:58 18
In the above code example, Since we used the with statement, we don’t need to worry about opening and closing the zip file.
Zipping a File in Python
We can zip a specific file by using the write() method from the zipfile module.
Example of zipping a file in Python
from zipfile import ZipFile import os print(f"Before zipping: {os.listdir()}") file = "Geeks.zip" # zip file name with ZipFile(file, 'w') as zip: zip.write("PythonGeeks.txt") # zipping the file print("File successfully zipped") print(f"After zipping: {os.listdir()}") with ZipFile(file, 'r') as zip: zip.printdir()
Output
File successfully zipped
After zipping: [‘main.py’, ‘Geeks.zip’, ‘PythonGeeks.txt’]
File Name Modified Size
PythonGeeks.txt 2021-06-28 08:41:58 18
Zipping All Files in Python Directory
To zip all files in a directory, we need to traverse every file in the directory and zip one by one individually using the zipfile module.
We can use the walk() function from the os module to traverse through the directory.
Example of zipping all files in a directory in Python
from zipfile import ZipFile import os file = "Geeks.zip" # zip file name directory = "School" with ZipFile(file, 'w') as zip: for path, directories, files in os.walk(directory): for file in files: file_name = os.path.join(path, file) zip.write(file_name) # zipping the file print("Contents of the zip file:") with ZipFile(file, 'r') as zip: zip.printdir()
Output
File Name Modified Size
School/student5.txt 2021-06-28 12:25:36 0
School/student4.txt 2021-06-28 12:25:36 0
School/student3.txt 2021-06-28 12:25:36 0
School/student2.txt 2021-06-28 12:25:36 0
School/student1.txt 2021-06-28 12:22:36 0
Although the above code does the job, there is a more efficient way of zipping an entire directory. To do this, we use the shutil module instead of zipfile module.
Example of zipping all files in a directory in Python
from shutil import make_archive from zipfile import ZipFile file = "Geeks" # zip file name directory = "School" make_archive(file, "zip", directory) # zipping the directory print("Contents of the zip file:") with ZipFile(file+".zip", 'r') as zip: zip.printdir()
Output
File Name Modified Size
student5.txt 2021-06-28 12:25:36 0
student4.txt 2021-06-28 12:25:36 0
student3.txt 2021-06-28 12:25:36 0
student2.txt 2021-06-28 12:25:36 0
student1.txt 2021-06-28 12:22:36 0
Extracting a File from Python Zip File
The module zipfile contains the method extract() to extract a certain file from the zip file.
Example of extracting a file from the zip file in Python
from zipfile import ZipFile import os print(f"Before extracting: {os.listdir()}") file = "Geeks.zip" with ZipFile(file, 'r') as zip: zip.extract('student1.txt') print("File successfully extracted") print(f"After extracting: {os.listdir()}")
Output
File successfully extracted
After extracting: [‘main.py’, ‘student1.txt’, ‘Geeks.zip’]
Extracting All Files from the Zip Directory
Instead of extracting one file at a time, we can extract all files at once by using the method extractall() from the zipfile module.
Example of extracting all files from the zip directory in Python
from zipfile import ZipFile import os print(f"Before extracting: {os.listdir()}") file = "Geeks.zip" with ZipFile(file, 'r') as zip: zip.extractall() print("File successfully extracted") print(f"After extracting: {os.listdir()}")
Output
File successfully extracted
After extracting: [‘main.py’, ‘student5.txt’, ‘student4.txt’, ‘student3.txt’, ‘student2.txt’, ‘student1.txt’, ‘Geeks.zip’]
Accessing the Info of a Zip File
We can use infolist() method from the zipfile module to get information on a zip file.
The method returns a list containing the ZipInfo objects of members in the zip file.
Example of using infolist() in Python
from zipfile import ZipFile from datetime import datetime file = "Geeks.zip" with ZipFile(file, 'r') as zip: info = zip.infolist()[1] print(f"File: {info.filename}") print(f"Zip Version: {info.create_version}") print(f"Last Modified Time: {datetime(*info.date_time)}") print(f"System: {info.create_system}") print(f"Compressed File Size: {info.compress_size} bytes") print(f"Uncompressed File size: {info.file_size} bytes") print(f"Compressed Type: {info.compress_type}")
Output
Zip Version: 20
Last Modified Time: 2021-06-28 12:25:36
System: 3
Compressed File Size: 2 bytes
Uncompressed File size: 0 bytes
Compressed Type: 8
Adding a File to an Existing Zip File
Opening the zip file in append mode ‘a’ instead of write mode ‘w’ enables us to add files to the zip file without replacing the existing files.
Example of adding files to an existing zip file in Python
from zipfile import ZipFile file = "Geeks.zip" print("Before Appending: ") with ZipFile(file, 'r') as zip: zip.printdir() with ZipFile(file, 'a') as zip: zip.write('student6.txt') print("After Appending: ") with ZipFile(file, 'r') as zip: zip.printdir()
Output
File Name Modified Size
student5.txt 2021-06-28 12:25:36 0
student4.txt 2021-06-28 12:25:36 0
student3.txt 2021-06-28 12:25:36 0
student2.txt 2021-06-28 12:25:36 0
student1.txt 2021-06-28 12:22:36 0
After Appending:
File Name Modified Size
student5.txt 2021-06-28 12:25:36 0
student4.txt 2021-06-28 12:25:36 0
student3.txt 2021-06-28 12:25:36 0
student2.txt 2021-06-28 12:25:36 0
student1.txt 2021-06-28 12:22:36 0
student6.txt 2021-07-02 23:33:38 0
Checking Whether a File is Zip File in Python
The function is_zipfile() is used to check whether a file is a zip file or not.
We need to pass the filename of the file that we want to check.
It returns True if the passed file is zip, otherwise, it returns False.
Example of using is_zipfile() in Python
import zipfile file1 = "Geeks.zip" file2 = "student1.txt" print(zipfile.is_zipfile(file1)) print(zipfile.is_zipfile(file2))
Output
False
Methods of Python ZipFile Object
namelist()
The function is used to view all files in a zip file. It returns a list containing the names of all files in a zip file including the files present in the sub-directories.
Example of using namelist() in Python
from zipfile import ZipFile file = "Geeks.zip" with ZipFile(file, 'r') as zip: print(zip.namelist())
Output
setpassword(pwd)
The function is used to set a password to a zip file. We need to pass a byte string containing the password. The passed password will be set to the zip file. It has no return value.
Example of using setpassword() in Python
from zipfile import ZipFile file = "Geeks.zip" with ZipFile(file, 'r') as zip: print(zip.setpassword("File123".encode()))
Output
testzip()
This function verifies all of the files in the archive for CRCs and file headers, then provides the name of the first problematic file. It returns None if there isn’t any.
Example of using testzip() in Python
from zipfile import ZipFile file = "Geeks.zip" with ZipFile(file, 'r') as zip: print(zip.testzip())
Output
writestr()
The function is used to write a new file with new data intp a zip file. We need to pass a string containing the file name and a string or byte string containing the data of the new file. The passed file containing the passed data will be created in the zip file. It has no return value.
Example of using writestr() in Python
from zipfile import ZipFile file = "Geeks.zip" with ZipFile(file, 'w') as zip: print(zip.writestr("new.txt", "PythonGeeks")) zip.printdir()
Output
File Name Modified Size
new.txt 2021-07-10 08:18:45 11
Attributes of Python ZipFile Object
debug
The attribute returns an integer containing the level of debug output we need to use. The returned value 0 represents no output while the 3 represents most output.
Example of using debug in Python
from zipfile import ZipFile file = "Geeks.zip" with ZipFile(file, 'r') as zip: print(zip.debug)
Output
comment
The attribute returns a byte string containing the comment supplied with the zip file.
Example of using comment in Python
from zipfile import ZipFile file = "Geeks.zip" with ZipFile(file, 'r') as zip: print(zip.comment)
Output
Python Interview Questions on Python Zip Files
Q1. Write a program to print all the contents of the zip file ‘EmployeeReport.zip’.
Ans 1. Complete code is as follows:
from zipfile import ZipFile with ZipFile('EmployeeReport.zip', 'r') as file: file.printdir()
Output
Efficiancy.csv 2021-05-20 02:59:22 226
Salary.csv 2021-05-20 02:59:22 226
Attendance.csv 2021-05-20 02:59:22 226
Q2. Write a program to zip a directory ‘EmployeeReport’ without using any loops.
Ans 2. Complete code is as follows:
from shutil import make_archive make_archive('EmployeeReport', 'zip', 'EmployeeReport') print("EmployeeReport.zip is created")
Output
Q3. Write a function to check whether a list of files is zip files or not. The function should return True if all files in the list are zip files, otherwise, it should return False.
Ans 3. Complete code is as follows:
from zipfile import is_zipfile def check_zip(files): return all(list(map(is_zipfile, files))) print(check_zip(['EmployeeReport.zip', 'Geeks.zip'])) print(check_zip(['student6.txt', 'Geeks.zip']))
Output
False
Q4. Write a program to extract the zip file ‘EmployeeReport.zip’.
Ans 4. Complete code is as follows:
from zipfile import ZipFile with ZipFile("EmployeeReport.zip", 'r') as file: file.extractall() print("Extracted Zip File")
Output
Q5. Write a program to add three files to an existing zip file ‘EmployeeReport.zip’. The three files are: ‘file1.txt’, ‘file2.txt’, and ‘file3.txt’.
Ans 5. Complete code is as follows:
from zipfile import ZipFile files = ['file1.txt', 'file2.txt', 'file3.txt'] zip_file = 'EmployeeReport.zip' with ZipFile(zip_file, 'a') as zip: for file in files: zip.write(file) print("Files Added")
Output
Quiz on Zip Files in Python
Conclusion
In this article, we learned how to create, modify and append zip files using Python. We discussed various ways of zipping a directory. We also learned how to check whether a file is a zip file or not using Python. Moreover, if you have any comments, kindly leave them in the comments section.