This article mainly describes how to compress and decompress the zip file in Python. This article provides the instance code directly. For more information, refer to the zip file, which is one of the frequently used packaging formats, the efficiency of decompressing and compressing zip files in python is remarkable. Decompress the zip file in python:
The code is as follows:
#/Usr/bin/python
# Coding = UTF-8
Import OS, sys, time
Import zipfile
Filename = 'callofdutyblackopszombies_1349649132343_my.zip '# file to be decompressed
Filedir = 'data/'# directory to which the package is extracted
R = zipfile. is_zipfile (filename)
If r:
Starttime = time. time ()
Fz = zipfile. ZipFile (filename, 'r ')
For file in fz. namelist ():
Print (file) # print the directory in the zip archive
Fz. extract (file, filedir)
Endtime = time. time ()
Times = endtime-starttime
Else:
Print ('This file is not zip file ')
Print ('Times '+ str (times ))
The compressed python folder is zip.
The code is as follows:
#/Usr/bin/python
# Coding = UTF-8
Import OS
Import zipfile
Import sys
Try:
Import zlib
Compression = zipfile. ZIP_DEFLATED
Except t:
Compression = zipfile. ZIP_STORED
Path = 'data/'# directory of the document to be compressed
Start = path. rfind (OS. sep) + 1
Filename = 'callofdutyblackopszombies_1349649132343_my.zip '# compressed file name
Z = zipfile. ZipFile (filename, mode = "w", compression = compression)
Try:
For dirpath, dirs, files in OS. walk (path ):
For file in files:
If file = filename or file = "zip. py ":
Continue
Print (file)
Z_path = OS. path. join (dirpath, file)
Z. write (z_path, z_path [start:])
Z. close ()
Except t:
If z:
Z. close ()