Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing a specific timestamp for files in pythons zipfile

Is it possible to force a specific timestamp for a file when adding it to a zipfile?

Something along these lines:

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

Can I change the ZipInfo on a member of a zipfile?

like image 761
dantje Avatar asked Jun 20 '12 07:06

dantje


1 Answers

Looking at the source for ZipFile.write() in CPython 3.7, the method always gets its ZipInfo by examining the file on disk—including a bunch of metadata like modified time and OS-specific attributes (see the ZipInfo.from_file() source).

So, to get around this limitation, you'll need to provide your own ZipInfo when writing the file—that means using ZipFile.writestr() and giving it both a ZipInfo and the file data you read from disk, like so:

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())

Alternatively, if you only want to modify the ZipInfo's date, you could get it from ZipInfo.from_file() and just reset its date_time field:

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

This is better in the general case where you do still want to preserve special OS attributes.

like image 130
s3cur3 Avatar answered Sep 19 '22 20:09

s3cur3