Unzip all zipped files in a folder to that same folder using Python 2.7.5

Below is the code that worked for me:

import os, zipfile

dir_name = 'C:\\SomeDirectory'
extension = ".zip"

os.chdir(dir_name) # change directory from working dir to dir with files

for item in os.listdir(dir_name): # loop through items in dir
    if item.endswith(extension): # check for ".zip" extension
        file_name = os.path.abspath(item) # get full path of files
        zip_ref = zipfile.ZipFile(file_name) # create zipfile object
        zip_ref.extractall(dir_name) # extract file to dir
        zip_ref.close() # close file
        os.remove(file_name) # delete zipped file

Looking back at the code I had amended, the directory was getting confused with the directory of the script.

The following also works while not ruining the working directory. First remove the line

os.chdir(dir_name) # change directory from working dir to dir with files

Then assign file_name as

file_name = dir_name + "/" + item

Leave a Comment