In this tutorial, we will use an example to show you how to unzip files using python zipfile package.
1.Install zipfile
pip install zipfile
2.Import library
from zipfile import ZipFile
3.Start unzip files
test_file_name = "my_files.zip" with ZipFile(test_file_name, 'r') as zip: zip.printdir() zip.extractall()
In this example, we will use zip.extractall() function to unzip zip file to the current folder. You also can unzip files to other folder using zip.extractall(). For example:
with ZipFile('my_files.zip', 'r') as zip: zip.extractall('temp') print('File is unzipped in temp folder')
This example code will unzip file to temp folder.
Look at this example code:
with ZipFile('my_files.zip', 'r') as obj_zip: FileNames = obj_zip.namelist() for fileName in FileNames: if fileName.endswith('.txt'): zipObj.extract(fileName, 'temp_txt')
This example will only unzip .txt files to temp_txt folder.