簡體   English   中英

如何解壓縮相同子目錄但不同文件夾中的文件

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

my_directory我有 3 個文件夾(NY、AMS、MAD)。 每個文件夾都有 1 個或多個壓縮文件。 我還有一個名為my_counterpart目錄。 這個是空的。

使用下面的代碼我試圖:

  1. 收集所有 3 個文件夾和它們擁有的壓縮文件。
  2. 將 3 個文件夾復制到my_counterpart + 解壓縮它們擁有的文件。

這是我的代碼:

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) 

我知道問題出在哪里, dirs不是字符串而是列表。 但是我似乎無法解決它。 這里有人可以指導我嗎?

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

變量my_counterpart是否計入新文件夾的路徑? 如果是,那么您為什么要向其添加其他內容,例如dirs 離開它已經可以做你想讓它做的事情。 剩下要做的是創建文件夾結構並提取到新創建的文件夾結構中:

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) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM