Use the writestr() method to Python zipfile write. It adds a string of bytes to the archive directly. he mode parameter should be 'r'
to read an existing file, 'w'
to truncate and write a new file
with ZipFile('spam.zip', 'w') as myzip: myzip.write('eggs.txt')
Python zipfile write
A simple example code writing the data to a file, then adding that file to the ZIP archive.
import zipfile
msg = 'This data did not exist in a file before being added to the ZIP file'
zf = zipfile.ZipFile('zipfile_writestr.zip',
mode='w',
compression=zipfile.ZIP_DEFLATED,
)
try:
zf.writestr('from_string.txt', msg)
finally:
zf.close()
print('zipfile_writestr.zip')
zf = zipfile.ZipFile('zipfile_writestr.zip', 'r')
print
zf.read('from_string.txt')
Output:
Do comment if you have any doubts or suggestions on this Python zipfile topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.