如何避免在压缩文件时创建子文件夹?
How to avoid subfolders creation while zipping files?
我正在尝试将列表 localpath_list
中的文件压缩到一个 zip 文件`reports.zip.
它按预期工作,但是当我提取 reports.zip
文件时,其中创建了文件夹。
即所有 .xls 文件都在 files/sample/
.
下
我需要的只是没有任何文件夹结构的 .xls 文件。
localpath_list = ["files/sample/sample1.xls", "files/sample/sample2.xls", "files/sample/sample3.xls"]
with zipfile.ZipFile(fr"downloads/reports.zip", 'w') as zipF:
for file in localpath_list:
zipF.write(file, compress_type=zipfile.ZIP_DEFLATED)
Write the file named filename to the archive, giving it the archive name arcname (by default, this will be the same as filename, ...
所以你应该使用:
zipF.write(file, arcname=os.path.basename(file), compress_type=zipfile.ZIP_DEFLATED)
如果计划扩展功能(包括来自多个文件夹的文件),您应该注意重复的文件基名(在不同的文件夹中)。
我正在尝试将列表 localpath_list
中的文件压缩到一个 zip 文件`reports.zip.
它按预期工作,但是当我提取 reports.zip
文件时,其中创建了文件夹。
即所有 .xls 文件都在 files/sample/
.
我需要的只是没有任何文件夹结构的 .xls 文件。
localpath_list = ["files/sample/sample1.xls", "files/sample/sample2.xls", "files/sample/sample3.xls"]
with zipfile.ZipFile(fr"downloads/reports.zip", 'w') as zipF:
for file in localpath_list:
zipF.write(file, compress_type=zipfile.ZIP_DEFLATED)
Write the file named filename to the archive, giving it the archive name arcname (by default, this will be the same as filename, ...
所以你应该使用:
zipF.write(file, arcname=os.path.basename(file), compress_type=zipfile.ZIP_DEFLATED)
如果计划扩展功能(包括来自多个文件夹的文件),您应该注意重复的文件基名(在不同的文件夹中)。