Import gzip# Compression g = gzip. Gzipfile (filename= "", mode= ' WB ', Compresslevel=9, Fileobj=open (R ' r:\test.log.gz ', ' WB ')) G.write (open (R ' R:\test.log '). Read ()) g.close () #解压g = gzip. Gzipfile (mode= ' RB ', Fileobj=open (R ' r:\popopo.gz ', ' RB ')) Open (R ' R:\test.log ', ' WB '). Write (G.read ())
Import Osimport tarfile# compression, create tar.gz package # Create ZIP package name tar = Tarfile.open ("/tmp/tartest.tar.gz", "W:gz") #创建压缩包for Root,dir,files In Os.walk ("/tmp/tartest"): For file in Files:fullpath = Os.path.join (root,file) tar.add (FullPath) tar.close () # Unzip the tar.gz package method one: Unzip to the specified directory tar = Tarfile.open (Tar_path, "r:gz") File_names = Tar.getnames () for file_name in File_names:tar.ext Ract (File_name,target_path) Tar.close () method Two: tar = Tarfile.open ("tartest.tar.gz") tar.extract ("/tmp") Tar.close ()
Python decompression and compression code for ZIP and tar.gz