python - 强制pythons zipfile中文件的特定时间戳

标签 python python-zipfile

在将文件添加到 zip 文件时是否可以强制为文件指定特定的时间戳?

沿着这些线的东西:

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

我可以更改压缩文件成员的 ZipInfo 吗?

最佳答案

查看the source for ZipFile.write() in CPython 3.7 , 该方法总是通过检查磁盘上的文件来获取其 ZipInfo — 包括一堆元数据,如修改时间和操作系统特定的属性(参见 the ZipInfo.from_file() source )。

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

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

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

info = ZipInfo.from_file('eggs.txt')
info.date_time = (1980, 1, 1, 0, 0, 0)

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

关于python - 强制pythons zipfile中文件的特定时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11115140/

相关文章:

python - Pandas:根据条件求和字符串

python - 在 Django 中注册自定义过滤器

python - 我如何使用 GAE 和 Nosetest 模拟用户?

python - Web2py - 尝试从没有 'for' 句子的 rows 对象获取值

python - 如何使用 zipfile 将多个 DataFrame 打包到一个文件中

Python 在压缩大文件时使用 ZIP64 扩展名

python - 基于 Pandas Dataframe 中的多列计算公式 - 但不创建许多中间列

python - 无论操作系统如何,Python zipfile 是否始终使用 posixpath 文件名?

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

arcname 的 python zipfile 编码