我正在尝试将列表 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)
最佳答案
根据:[Python.Docs]: zipfile - ZipFile.write(filename, arcname=None, compress_type=None, compresslevel=None) (强调是我的):
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)
如果计划扩展功能(以包含多个文件夹中的文件),则应注意重复的文件基本名称(在不同的文件夹中)。
关于python - 如何避免在压缩文件时创建子文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70424735/