How to Unzip Files Using Python Script

unzip-files-using-python-simplemsoffice

This is a very useful script to unzip all zip files in a folder with a single click. You can also run this script from the batch file. With this python script code, you can unzip a single zip file and multiple zip files. And with small changes, you can either extract the files in the same or in some other folder.

Suppose you have a single zip file “RawData.zip” containing some other files placed in the “Source Folder” in C: drive. If you want to unzip files in the same directory using Python script then follow the below steps:

Step 1: Open Notepad in your system.

Step 2: Copy below code in Notepad:

1
2
3
import zipfile
zip = zipfile.ZipFile("rawdata.zip")
zip.extractall()

or

1
2
3
4
from zipfile import ZipFile
file_name = "RawData.zip"
with ZipFile(file_name, 'r') as zip:
    zip.extractall()

or
below code is with an explanation, you can also copy and use the below code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Import modules to work on zip file
from zipfile import ZipFile
 
# mention the zip file name
file_name = "RawData.zip"
 
# open the zip file in READ mode
with ZipFile(file_name, 'r') as zip:
    # display list of the contents in zip file
    zip.printdir()
 
    # unzipping all the files
    print('Unzipping all the files in zip file...')
    zip.extractall()
    print('Unzip Completed!')

Step 4: Save the Notepad file in the “Source Folder” and give any name like “unzipfile.py“.

Now you can run a python script file and it will unzip rawdata.zip files in the same folder i.e. “Source Folder“.

Note:- To edit a batch file, right-click on it and select Edit or you can open the python script in Notepad, and after editing you can save it.

If you want to unzip or extract the zip file into a different directory, like “C:\Source Folder\Batch1\” then mention the directory name in () as below:

1
zip.extractall('Batch1')

or

1
2
3
import zipfile
zip = zipfile.ZipFile("rawdata.zip")
zip.extractall(‘Batch1’)

Read: How to run Python Script using Batch File?

Unzip all available zip files using Python
If have multiple zip files with different names placed in “C:\Source Folder\” like below:

RawData.zip
RawData1.zip
newdata.zip
newdata1.zip

and you want to unzip all these files in “C:\Source Folder\” then use the code below:

1
2
3
4
5
6
7
8
9
10
import zipfile
from os import listdir
from os.path import isfile, join
directory = '.'
onlyfiles = [f for f in listdir(directory) if isfile(join(directory, f))]
for o in onlyfiles:
    if o.endswith(".zip"):
        zip = zipfile.ZipFile(o, 'r')
        zip.extractall(directory)
        zip.close()

 

0 Comments

Leave a Comment

Your email address will not be published. Required fields are marked *