Python's ZipFile provides a very convenient way to compress and decompress zip files.
For example, in the directory where the py script resides, there are the following files:
Copy the Code code as follows:
Readability/readability.js
Readability/readability.txt
Readability/readability-print.css
Readability/sprite-readability.png
Readability/readability.css
Compress the files in the readability directory into the Readability.zip file of the directory where the script resides, keep the same file structure, and then print out a list of the files for the generated compressed package, and then extract the files separately into the output directory of the directory where the script is located and output/in two different ways The Bak directory.
The script is as follows:
#!/usr/vin/env python# coding:utf-8 "" "Compress and Decompress zip file" "Import osimport zipfiledef compress (Zip_file, input_dir): F_zip = Zi Pfile. ZipFile (Zip_file, ' W ') for root, dirs, files in Os.walk (Input_dir): For F in Files: # Get file-relative path, build the same directory structure within the compact package Abs_path = Os.path.join (Os.path.join (root, f)) Rel_path = Os.path.relpath (Abs_path, Os.path.dirname (Input_dir)) F_zip.write (Abs_path, Rel_path, ZipFile. zip_stored) def extract (Zip_file, output_dir): F_zip = ZipFile. ZipFile (Zip_file, ' R ') # Unzip all files to the specified directory F_zip.extractall (output_dir) # Unzip the file to the specified directory individually for f in F_zip.namelist (): F_zip.ex Tract (f, os.path.join (Output_dir, ' Bak ')) def printdir (zip_file): F_zip = ZipFile. ZipFile (Zip_file, ' R ') print ' = = Printdir () ============================ ' F_zip.printdir () print print ' = = NameList () ============================ ' for F in F_zip.namelist (): print fif __name__ = = ' __main__ ': zip_file = ' Readability.zi P ' Compress (Zip_file, Os.path.join (OS.GETCWD (), ' readability ')) PrintdirziP_file) Extract (zip_file, ' output ')