Extract files from a ZIP file in Python
Hello friends, many times you must have uncompressed a ZIP file using an external tool. In this tutorial, I will tell you how you can extract files from a ZIP file using Python
Extract files from a ZIP file in Python
To uncompress a ZIP file we can use Python’s inbuilt functions, zipfile.ZipFile
and shutil
.
You can check: Create a ZIP file and add files to it using Python
1 . Using zipfile.ZipFile
One needs to read the ZIP file, to be able to extract files from the file. I have used the ZipFile object and specified the path to my ZIP file and the mode of access. I have opened the file in ‘r’ i.e. the read mode. You can also alias the name of the read file by using the as keyword. I have aliased my file as zip_file. I have not added a password to my ZIP file, but in case there is one you can add the parameter pwd
and mention your password as a string.
There are two ways you can extract files. One is the extractall()
function and the other one being extract()
. The former uncompress the whole ZIP file at once. You can also specify the path to the target directory. By default, it’s the current directory.
Code :
with ZipFile("{ZIP file path}", 'r') as zip_file: zip_file.extractall()
Output :
extract()
function returns only the file that you mention. In my example, I have specified ‘7.png’ as the file that I want to uncompress. Similarly, you can specify the path of the target directory.
Code :
with ZipFile("{ZIP file path}", 'r') as zip_file: zip_file.extract('7.png')
Output :
2 . Using shutil
You can use the shutil
module to uncompress a ZIP file. The first thing I have done in my code is to import the module. I have taken a temporary variable filepath
to store my ZIP file’s path. unpack_archive() function helps you to uncompress the ZIP file. I have given the variable filepath
as an argument, but you can pass the path’s value directly as well.
Code :
import shutil filename = "C:\\Users\\PC\\Desktop\\intern_python\\ZIP files\\My ZIP file.zip" shutil.unpack_archive(filename, extract_dir = "C:\\Users\\PC\\Desktop\\intern_python\\ZIP files")
extract_dir takes the value of the target directory. If no value is specified, the current directory is the folder where all the uncompressed files are stored.
Output :
Now you can easily uncompress a ZIP file using Python.
Leave a Reply