TangerCity
TangerCity

Reputation: 845

How to unzip files in the same subdirectories but a different folder

In my_directory I have 3 folders (NY, AMS, MAD). Each folder has 1 or more zipped files. I also have an other directory named my_counterpart. This one is empty.

With below code Im trying to:

  1. Collect all the 3 folders and the zipped files they posses.
  2. Copy the 3 folders to my_counterpart + unzipp the files they posses`.

This is my code:

pattern = '*.zip'
for root, dirs, files in os.walk(my_directory): 
    for filename in fnmatch.filter(files, pattern): 
        path = os.path.join(root, filename) 
        new = os.path.join(my_counterpart, dirs)
        zipfile.ZipFile(path).extractall(new) 

I know where the fault lies, dirs is not a a string but a list. However I can't seem to solve it. Someone here who can guide me?

TypeError: join() argument must be str or bytes, not 'list'

Upvotes: 1

Views: 90

Answers (1)

Mantas Kandratavičius
Mantas Kandratavičius

Reputation: 1498

Does the variable my_counterpart countain the path to new folder? If yes then why would you add something else to it like dirs? Leaving it out already does what you want it to do. What's left to do is to create the folder structure and extract into that newly created folder structure:

pattern = '*.zip'
for root, dirs, files in os.walk(my_directory): 
    for filename in fnmatch.filter(files, pattern): 
        path = os.path.join(root, filename)

        # Store the new directory so that it can be recreated
        new_dir = os.path.normpath(os.path.join(os.path.relpath(path, start=my_directory), ".."))

        # Join your target directory with newly created directory
        new = os.path.join(my_counterpart, new_dir)

        # Create those folders, works even with nested folders
        if (not os.path.exists(new)):
            os.makedirs(new)

        zipfile.ZipFile(path).extractall(new) 

Upvotes: 1

Related Questions