Python 的 zipfile 模块无法更新条目

标签 python python-zipfile

<分区>

我想使用 python 更新 zip 文件中的条目 zipfile模块。 我的问题是这会生成一个新条目。

请假设我有这段代码:

from zipfile import ZipFile,ZIP_DEFLATED
with ZipFile("myfile.zip","w") as z:
    z.writestr("hello.txt", "the content of hello.txt", ZIP_DEFLATED)
    ###  how to update the hello.txt file here ?
    z.writestr("hello.txt", "the content of hello.txt", ZIP_DEFLATED)

在此之后实际的 zip 文件有两个条目而不是一个:

$ unzip -l myfile.zip 
Archive:  myfile.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
       24  2013-02-19 22:48   hello.txt
       24  2013-02-19 22:48   hello.txt
---------                     -------
       48                     2 files
$ python --version
Python 3.3.0
$

我知道写一个完整的新文件的方法,但这会 如果内容很大,会花费很多时间。

zip(1) 实用程序可以做到这一点(使用“-u”选项)那么为什么 python 不行呢? 有什么方法我仍然可以使用 python 实现此目的吗?

最佳答案

zip 格式没有任何简单的方法来删除或替换存档中的文件。可能有一些图书馆可以就地这样做,但我不知道有一个。

但是等等:

the zip(1) utitly can do this ( using the "-u" option) so why not python?

首先,-u 所做的只是告诉它“只有在时间戳不是更新的情况下才替换现有文件”,这在这里并不重要。没有 -u 它仍然会,默认命令是 add,它在不检查时间戳的情况下做同样的事情:

Update existing entries and add new files. If the archive does not exist create it. This is the default mode.

但是,更重要的是,作为 the manpage you referenced明确地说:

Zip files. When changing an existing zip archive, zip will write a temporary file with the new contents, and only replace the old one when the process of creating the new version has been completed without error.

这正是您想要做的:将一个完整的新文件写入一个临时位置,然后用新文件替换原来的文件。

如果您需要让它在 Windows 上运行,这可能会有点痛苦。 (如果没有,只需使用 tempfile.NamedTemporaryFileos.rename。)但您已经知道如何去做:

I know of the method to write a complete new file, but this would take much time if the content is big.

只不过 zip -u 花费太多时间。

关于Python 的 zipfile 模块无法更新条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14968496/

相关文章:

用于 JSON 序列化的 Python RFC 3339 格式

python - 如何创建加密的 ZIP 文件?

python - 从 URL 读取 ZipFile 到 StringIO 并用 panda.read_csv 解析

python - Zipfile python模块字节大小差异

Python zipfile compress_size 返回 'int' 对象不可调用

python - 在给定条件下向 pandas DataFrame 添加值

python - elasticsearch-dsl-py 中的 GeoPoint 字段类型

python - 将一个数据框中的行中的多个字符串匹配到另一个数据框中的行

python - 从csv读取列表,len只显示一项

Python - 使用 zipfile 模块压缩目录中的所有文件