python - 如何避免在压缩文件时创建子文件夹?

标签 python python-3.x zip python-zipfile

我正在尝试将列表 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/

相关文章:

python - Python 中的元组真的是不可变的吗?

jar - 正确解码 zip 条目文件名——CP437、UTF-8 还是?

java - 将 zip 文件编码为 Base64,而不在文件系统上写入 zip

python - 数据流: update BigQuery rows with python pipeline

python - pandas to_sql 方法给出日期列错误

python-3.x - 如何使用 Docker API Python 客户端构建图像?

php - 从压缩文件中获取图像的高度和宽度

python - 什么时候在 Python 中使用线程?

python - Boost Python 重写相等运算符

python - 数的质因数的表示方法