简体   繁体   中英

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 aa 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'

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM