python - 如何解压缩相同子目录但不同文件夹中的文件
问题描述
在my_directory
我有 3 个文件夹(NY、AMS、MAD)。每个文件夹有 1 个或多个压缩文件。我还有一个名为my_counterpart
. 这个是空的。
使用下面的代码我试图:
- 收集所有 3 个文件夹和它们拥有的压缩文件。
- 将 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)
推荐阅读
- oracle - 是否有一种自动方法可以将 Oracle 的连接语法 (+) 转换为标准连接语法?
- r - 在 ggplot 代码中使用 ifelse() 条件时出错
- excel - 条件格式 - 根据另一个单元格文本更改单元格颜色
- css - 如何一起使用 :before 和 :nth-child 选择器
- css - CSS媒体查询不起作用,我已经尝试了一切
- python - 如何根据列中唯一值的数量从字典中删除/删除数据框?
- javascript - 如何在其他地方使用变量的当前值?
- r - 根据组过滤多个事件
- r - 如何根据多列查找查找 data.frame 中最近的行?
- javascript - Google Cloud Speech API 与 Web Speech API 的单词错误率