python类库31[压缩与解压]
一 python压缩解压libs
zlib:infozip免费的压缩lib。
bzip2:读写bz压缩文件,与bzip2和bunzip2压缩程序兼容。
gzip: 读写gz压缩文件,与GNU压缩程序gzip和gunzip兼容。
zipfile:读写zip压缩文件,与zip,unzip,pkzip,pkunzip,winzip等程序兼容。
tar:读写tar包文件。7z等程序可以大包和解包tar。
二 zip压缩解压实例
import os
import zipfile
filename='c:/test.zip'
curdir="C:/test/"
os.chdir(curdir)
#Create the zip file
tFile = zipfile.ZipFile(filename, 'w')
#Write directory contents to the zip file
files = os.listdir(curdir)
for f in files:
tFile.write(f)
#List archived files
for f in tFile.namelist():
print ("Added %s" % f)
#close the zip file
tFile.close()
#whether the file is zip file
print(zipfile.is_zipfile(filename))
#list all file in the zip file
tFile = zipfile.ZipFile(filename, 'r')
for file in tFile.namelist():
print(file)
#List info for archived file
tinfo=tFile.getinfo("test.log")
print(tinfo.comment)
print(tinfo.compress_size)
print(tinfo.date_time)
print(tinfo.file_size)
print(tinfo.compress_type)
print(tinfo.filename)
#Read zipped file into a buffer
buffer = tFile.read("test.log")
print (buffer)
#close the zip file
tFile.close()
完!