强制为pythons zipfile中的文件指定特定的时间戳

dan*_*tje 6 python zipfile

将文件添加到zipfile时是否可以为文件强加特定时间戳?

遵循以下原则:

with ZipFile('spam.zip', 'w') as myzip:
  myzip.write('eggs.txt', date_time=(1752, 9, 9, 15, 0, 0))
Run Code Online (Sandbox Code Playgroud)

我可以在zip文件的成员上更改ZipInfo吗?

s3c*_*ur3 12

查看CPython 3.7 中的源代码ZipFile.write(),该方法始终ZipInfo通过检查磁盘\xe2\x80\x94 上的文件来获取它,包括一堆元数据,例如修改时间和特定于操作系统的属性(请参阅源代码ZipInfo.from_file()

\n\n

因此,为了解决此限制,您需要ZipInfo在写入文件时提供自己的\xe2\x80\x94,这意味着使用ZipFile.writestr()并为其提供 aZipInfo和从磁盘读取的文件数据,如下所示:

\n\n
from zipfile import ZipFile, ZipInfo\nwith ZipFile(\'spam.zip\', \'w\') as myzip, open(\'eggs.txt\') as txt_to_write:\n    info = ZipInfo(filename=\'eggs.txt\',\n                   # Note that dates prior to 1 January 1980 are not supported\n                   date_time=(1980, 1, 1, 0, 0, 0))\n    myzip.writestr(info, txt_to_write.read())\n
Run Code Online (Sandbox Code Playgroud)\n\n

或者,如果您只想修改ZipInfo\ 的日期,您可以从中获取它ZipInfo.from_file()并重置其date_time字段:

\n\n
info = ZipInfo.from_file(\'eggs.txt\')\ninfo.date_time = (1980, 1, 1, 0, 0, 0)\n
Run Code Online (Sandbox Code Playgroud)\n\n

在您仍然希望保留特殊操作系统属性的一般情况下,这会更好。

\n

  • +1 两个 zip 文件具有相同哈希值的问题,其中一个是通过重新压缩另一个 zip 文件的内容而创建的,花了我 2 个小时,但没有找到解决方案。你的回答就是我问题的解决方案。谢谢。 (4认同)
  • @sema 这也正是我的用例。我需要能够创建可复制的 ZIP,这样当从具有相同内容的文件创建时,ZIP 存档将是逐位相同的。很高兴我能帮助别人。:) (2认同)