Create a compressed file

Create a compressed file

Reprint indicate source: Link to this article Come from osnosn's blog , written on May 8, 2020

  • ZipFile's compression = the default is zip [stored (only storage but not compression).
    So it should be specified as zip ﹐ expanded (zip algorithm), or zip ﹐ LZMA (LZMA algorithm, high compression rate, which is a little bit slower)
    • compresslevel = more than py3.7 is required.
  • Write to a file. You can use write() or writestr()
    • With write(), you don't need to set the file modification time yourself.

Example 1, create zip

import zipfile
import time

orgfilename='Original filename to be compressed'
fstat=os.stat(orgfilename) # Get file modification time
bname=os.path.basename(orgfilename) #Remove path
comment='This is a test comment.\n This is line 2.' #Limit 65535 bytes

fzip=zipfile.ZipFile(orgfilename+'.zip','w',compression=zipfile.ZIP_DEFLATED) #py<=3.6
#fzip=zipfile.ZipFile(orgfilename+'.zip','w',compression=zipfile.ZIP_DEFLATED,compresslevel=6) #py>=3.7
fzip.comment=comment.encode('utf-8')  # bytes, write the comment of the zip itself. Whenever you write, there is the end of the zip file.

with open(orgfilename,'rb') as fin:
    fzip.writestr('mydir/'+bname, # Write the file to zip, which only adds a layer of directory mydir
finfo=fzip.getinfo('mydir/'+bname) #Get the info of this file
# Because the file is written through writestr(), the file modification time needs to be set manually
finfo.date_time=time.localtime(fstat.st_mtime)[0:6] # File modification time
finfo.comment=comment.encode('utf-8') #bytes, write the comment of the corresponding file. It actually exists at the end of the file.
fzip.close() #zip file creation complete

Example 2, notes

import json

#The annotation of zip file can be used in this way
comment=json.dumps(COMM,indent=2) #Look good with indent
fzip.comment=comment.encode('utf-8')  # bytes, write the comment of the zip itself

Example 3, read zip

import zipfile
from io import BytesIO
import json

zipname='zip File name of'
fzip=zipfile.ZipFile(zipname,'r') #Open zip file
comm=fzip.comment.decode('utf-8') # zip's own comments, read faster
print('===> zip comment:')
zipdata=json.loads(comm) # Get json data in comment
print('===> data from json:')

names=fzip.namelist()  #Get the list of files in the compressed file
finfo=fzip.getinfo(names[0]) #Read the properties of the first file
print('===> mtime of file:')
print('%02d-%02d-%02d %02d:%02d:%02d' % finfo.date_time) #File modification time
print('===> comment of file:')
print(finfo.comment.decode('utf-8')) #Notes to the file
fout=BytesIO([0])) #Read the contents of the first file and put it into memory

Reprint indicate source: Link to this article Come from osnosn's blog.

Tags: Python JSON

Posted on Sat, 09 May 2020 11:56:12 -0400 by rsassine