在将文件添加到 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/