Working with Zip File in Python(Writing)
Module in Python to write zip file:
The zipfile module can be used to manipulate ZIP archive files.Sometimes it is necessary to write
to a ZIP archive using data that did not come from an existing file. Rather than writing the data to
a file, then adding that file to the ZIP archive, you can use the writestr() method to add a string
of bytes to the archive directly.
Code:
from zipfile_infolist import print_info
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_info('zipfile_writestr.zip'
zf = zipfile.Zip File('zipfile_writestr.zip', 'r')
print zf.read('from_string.txt')
Output:
$ python zipfile_writestr_zipinfo.py
from_string.txt
Comment: Remarks go here
Modified: 2019-11-14 11:44:14
System: 0 (10 = Windows)
ZIP version: 20
Compressed: 62 bytes
Uncompressed: 64 bytes
A directory with such a format:
# importing required modules
def get_all_file_paths(directory):
file_paths = []
for root, directories, files in os.walk(directory):
for filename in files:
filepath = os.path.join(root, filename)
file_paths.append(filepath)
return file_paths