【发布时间】:2018-01-28 05:08:27
【问题描述】:
我正在尝试将几个子目录中的文件解压缩并复制到目标目录。这是我的代码。
import zipfile,fnmatch,os
rootPath = r"C:\\Temp\\Test\\source"
pattern = '*.zip'
for root, dirs, files in os.walk(rootPath):
for filename in fnmatch.filter(files, pattern):
zip_ref = zipfile.ZipFile(os.path.join(root, filename))
zip_ref.extractall(os.path.join("C:\\Temp\\Test\\dest"))
如您所见,我已解压缩源目录中的所有文件并将它们复制到 dest(ination) 目录。预期的最终结果应该是解压并复制 dest 目录中的 TXT 文件。(只有 txt 文件,没有目录)
我的代码运行良好,直到我找到源目录的结构(请参考下面的评论)
+--- [source]
|
+--- [subdir1]
| |
| +--- file1.zip # this zip file only contains a single txt file!
|
|
+--- [subdir2]
|
| +--- file2.zip # this zip file contains a directory which contains a txt file!
|
源目录中的大多数子目录看起来像 [subdir1],因此它们与我的代码完全兼容。但是也有一些例外,例如 [subdir2],其中 zip 文件不仅包含一个 txt 文件,而且还包含一个包含它的目录...... 这是当前代码下 dest 目录的样子。
+--- [dest]
|
+--- [subdir2]
| |
| +--- file2.txt
|
+--- file1.txt
|
有什么想法可以让 dest 目录中只有解压缩和复制的 TXT 文件吗? 我考虑先复制 zip 文件,然后将它们解压缩到 dest 目录中,但还没有找到解决方案....任何帮助将不胜感激!
【问题讨论】:
标签: python file directory copy unzip