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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With