如何在 Python 中使用 Zipfile 压缩具有扁平目录结构的文件? [英] How can I zip file with a flattened directory structure using Zipfile in Python?

查看:54
本文介绍了如何在 Python 中使用 Zipfile 压缩具有扁平目录结构的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ZipFile 包在 Python 中压缩文件.这是我的代码:

I'm using the ZipFile package to zip file in Python. Here's my code:

archive = zipfile.ZipFile(join(settings.ARCHIVES_DIR, 'test.zip'), "a")

for pdffile in glob.glob(join(settings.IBILLING_DIR, '*.pdf')):
    archive.write(pdffile)

archive.close()

我面临的问题是创建的 ZIP 文件包含目录结构.添加的文件添加了完整的路径,这意味着提取存档的用户也将最终获得目录结构.我想将文件添加到 ZIP,但没有任何目录结构.

The issue I'm facing is that the ZIP file that is created, contains a directory structure. The files that are added are added with the full the path which means that the user that extracts the archive, will also end up getting a directory structure. I'd like to the add files to the ZIP but without any directory structure.

我该怎么做?我在文档中没有找到此信息.

How can I do this? I didn't find this information in the docs.

谢谢

推荐答案

先添加

import os

然后将 archive.write 行修改为:

archive.write(pdffile, os.path.basename(pdffile))

这指定每个 pdf 应写入 zip 文件,其路径仅等效于您从中读取它的路径的文件名部分(通过指定 write() 调用的弧名参数).

This specifies that each pdf should be written into the zip file with a path equivalent to only the filename portion of the path from which you are reading it (by specifying the arcname parameter for the write() call).

但是请注意,这意味着如果您在不同目录中有两个同名的 PDF 文件,一个将覆盖另一个.

Note, however, that this means that if you have two PDF files with the same name in different directories, one will overwrite the other.

这篇关于如何在 Python 中使用 Zipfile 压缩具有扁平目录结构的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆