zip 文件是常用的压缩文件格式。 python zipfile模块提供了创建、读取、写入、追加等方法来进行zipfile文件操作。
常用ZIP64扩展,最大支持4G。支持解密文档,但是当前不支持创建加密文档,解密速度比较慢。
- ZipFile类,读取、写入ZIP文件。
- PyZipFile类,创建ZIP归档,可以包含Python库
- ZipInfo类,查看归档文件的信息,常用函数getinfo()和infolist()
常用函数:
ZipFile(file, mode=’r’, compression=ZIP_STORED, allowZip64=True),创建压缩文件
with ZipFile(‘spam.zip’, ‘w’) as myzip:
myzip.write(‘eggs.txt’)is_zipfile(filename),是否是压缩文件
ZipFile.open(name, mode=’r’, pwd=None, *, force_zip64=False),打开压缩文件
with ZipFile(‘spam.zip’) as myzip:
with myzip.open(‘eggs.txt’) as myfile:
print(myfile.read())ZipFile.close(),关闭,必须有,也可以用with语句,省略此句
- ZipFile.extract(member, path=None, pwd=None),解压指定文件到当前目录,也可指定目录
- ZipFile.extractall(path=None, members=None, pwd=None),解压所有文件
- ZipFile.setpassword(pwd),设置密码
- ZipFile.write(filename, arcname=None, compress_type=None),写
- ZipFile.read(name, pwd=None),读
压缩一个目录:
def zip_dir(dirname, zipfilename):
filelist = []
if os.path.isfile(dirname):
filelist.append(dirname)
else :
for root, dirs, files in os.walk(dirname):
for dir in dirs:
filelist.append(os.path.join(root,dir))
for name in files:
filelist.append(os.path.join(root, name))
with zipfile.ZipFile(zipfilename, "w") as zf:
for tar in filelist:
arcname = tar[len(dirname):]
print(tar + " -->rar: "+ arcname)
zf.write(tar,arcname)
解压的函数:
def unzip_dir(zipfilename, unzipdirname):
fullzipfilename = os.path.abspath(zipfilename)
fullunzipdirname = os.path.abspath(unzipdirname)
print("Start to unzip file %s to folder %s ..." % (zipfilename,unzipdirname))
#Check input
if not os.path.exists(fullzipfilename):
print("Dir/File %s is not exist!" % fullzipfilename)
return
if not os.path.exists(fullunzipdirname):
os.mkdir(fullunzipdirname)
#Start extract files
with zipfile.ZipFile(fullzipfilename,'r') as myzip:
myzip.extractall(fullunzipdirname)
print( "Unzip file succeed!")
参考: