user9476284
user9476284

Reputation: 150

behaviour of date of files when writing a zip file python

I want to write txt files and save them to a zipfile

The problem I'm facing - whenever I extract the file, the dates of the files are all 1 Jan 1980

here's the code

from zipfile import ZipFile

files = ['A.txt', 'B.txt', 'C.txt']

with ZipFile('example.zip','w') as myzip:
    for file_name in files:
        with myzip.open(file_name, 'w') as file:
            file.write('example text'.encode())

I would like to understand if this is expected behaviour and if there is anything I can do in the code so that the dates are correct.

Upvotes: 4

Views: 894

Answers (2)

一年又一年
一年又一年

Reputation: 91

To use ZipFile.open(, mode='w') adding a virtual file (which means it does not really exist on the disk), and importantly have a reasonable datetime tied to it (rather than some broken weird date back to 1980-01-01 or so)... — You may have a try to construct a ZipInfo model specified with date_time and use the model as the name argument to call ZipFile.open().

files = ['A.txt', 'B.txt', 'C.txt']

with zipfile.ZipFile(file='example.zip', mode='w', compression=zipfile.ZIP_DEFLATED) as fzip:
    for file_name in files:
        # create a ZipInfo model with date_time.
        file_info = zipfile.ZipInfo(
            filename=file_name,
            date_time=datetime.datetime.now().timetuple()[:6],
            # for demo purpose. may need carefully examine timezone in case of practice.
        )

        # important: explicitly set compress_type here to sync with ZipFile,
        # otherwise a bad default ZIP_STORED will be used.
        file_info.compress_type = fzip.compression

        # open() with ZipInfo instead of raw str as name to add the virtual file.
        with fzip.open(name=file_info, mode='w') as fbin:
            ...

BE CAREFUL: You have to explicitly set the ZipInfo model's compress_type attribute (to sync with ZipFile). Otherwise a default value compress_type=ZIP_STORED (which generally is a bad value) would be used! This attribute does take effect behind the scene but is not exposed by the constructor (__init__) of ZipInfo thus it could be easily got ignored.

Upvotes: 2

user9476284
user9476284

Reputation: 150

Changing the code to write the txt files first and then write each text file to the zipfile ensures the date is correct. But still not sure why the dates are all 1 Jan 1980 for the original code.

Here is the adjusted code.

from zipfile import ZipFile

files = ['A.txt', 'B.txt', 'C.txt']

with ZipFile('example.zip','w') as myzip:
    for file_name in files:
        with open(file_name, 'w') as file:
            file.write('example text')
        myzip.write(file_name)

Upvotes: 0

Related Questions