Tuesday, March 19, 2019

How to Unzip Files Using Python - Simple Step by Step Guide


Condition: Python should be installed in your system


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

Step 1: Open Notepad in your system.

Step 2: Copy below code in Notepad:

import zipfile
zip = zipfile.ZipFile("rawdata.zip")
zip.extractall()

or

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


or
below code is with explanation, you can also copy below code:

# 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 Notepad file in “Source Folder” and give any name like “unzipfile.py”.

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

Note:- If you want to edit batch file, then right click on it and then click on “Edit” or you can open python script in Notepad and after editing you can save.



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

zip.extractall(‘Batch1’)

or

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





How to unzip all available zip files using Python?

Suppose you 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 files in “C:\Source Folder\” then use code as below:

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()



***** End *****

No comments:

Post a Comment