首页 > 解决方案 > 如何解压缩相同子目录但不同文件夹中的文件

问题描述

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'

标签: pythonfilezipfile

解决方案


变量是否计算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) 

推荐阅读