-3

I have been using the following code to extract the files:

import os, zipfile

extension = ".zip"

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

The problem is that all the files inside the zip have the same name. For example:

Zip 1 has names, "File 1, File 2"

Whereas Zip 2 also has names "Files 1" and "File 2"

After extracting, all my files are getting overwritten by the next file.

Is there any solution to this?

I tried extracting files, expected the files to be extracted, but all the files got overridden.

khelwood
  • 55,782
  • 14
  • 81
  • 108

1 Answers1

0

Use os.mkdir("dir_name") with the same name as the Zip File and then Extract them in this new directory zip_ref.extractall("dir_name")

For eg:- Zip File => my_zip.zip

filename = my_zip.zip
os.mkdir(filename.strip(".zip"))

#rest of the code

zip_ref.extractall(filename.strip(".zip"))
KillerRebooted
  • 470
  • 1
  • 12