Search code examples
python-3.xzip

Unzip multiple zip files into different folders with a particular name


I have a folder which has 2500 zip files, I basically want to have each zip file unzipped and put in a folder with a name.

Below is what I tried. But i got this error KeyError: "There is no item named. Please suggest.

Thank you.

dir_name = 'March_2020_banners'
extension = ".zip"
new_dir = 'Unzipped_files'#
list containing all directories, note list dir returns a list
entries = os.listdir('March_2020_banners/')


# Extract all zip files


def extract_zip_Files():
  os.chdir(dir_name)# change directory from working dir to dir with files
  for item in entries: #loop through items in dir
  if item.endswith(extension):

    file_name = os.path.abspath(item)# get full path of files
    print('file is', file_name)
    zip_ref = zipfile.ZipFile(file_name)# create zipfile object
    zip_ref.extract(file_name, new_dir)# extract file to dir
    zip_ref.close()# close file


extract_zip_Files()


Solution

  • Well i got the solution for it. Here is what I did and it worked.

    def extract_zip_Files():
        os.chdir(dir_name)  # change directory from working dir to dir with files
        for item in entries:  # loop through items in dir
            if item.endswith(extension):  # check for ".zip" extension
                file_name = os.path.abspath(item)  # get full path of files
                print('file is', file_name)
                zip_ref = zipfile.ZipFile(file_name)  # create zipfile object
                zip_ref.extractall(cwd+"/unZipped/"+item)  # extract file to dir
                zip_ref.close()  # close file