#! /Usr/vin/env python # Coding: UTF-8 """ Compress and decompress zip files """ Import OS Import zipfile Def compress (zip_file, input_dir ): F_zip = zipfile. ZipFile (zip_file, 'w ') For root, dirs, files in OS. walk (input_dir ): For f in files: # Obtain the relative file path and create the same directory structure in the compressed 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 ') # Decompress all files to the specified directory F_zip.extractall (output_dir) # Decompress files one by one to the specified directory For f in f_zip.namelist (): F_zip.extract (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 f If _ name _ = '_ main __': Zip_file = 'readability.zip' Compress (zip_file, OS. path. join (OS. getcwd (), 'readability ')) Printdirzip_file) Extract (zip_file, 'output') </pre> |