how to set comment in python zipinfo

Viewed 1305

I finished the level 6 in python challenge with library zipfile and found that the answer was recorded in ZipInfo.comment. I wonder how to put text in this field. I have read the source code for python library zipfile but couldn't find any method to achieve it.

Dose anyone know about it?

1 Answers

You can write it when you create the ZipFile object:

with zipfile.ZipFile('myzip.zip', 'w') as zip:
    zip.write('file.py')
    zip.comment = b'This is my comment'

The text has to be entered as binary with prefix b

https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.comment

If your archive already exists, you can also use the mode a to append the comment alone:

with zipfile.ZipFile('myzip.zip', 'a') as zip:
    zip.comment = b'This is a new comment'

To set the comment on file zipped, you have to access the ZipInfo object like below, or create it with method from_file:

with zipfile.ZipFile('myzip.zip', 'w') as zip:
    zip.write('file.py')
    info = zip.getinfo('file.py')
    info.comment = b'zipped file comment'
Related