先说一下环境:windows 10,python3,pycharm2020.1
1、读取压缩文件
import os
import zipfile
filename = zipfile.ZipFile('abc.zip')
print(filename.namelist())
filename.close()
2、创建压缩文件
import zipfile, os
#压缩文件,w是写入
newzip = zipfile.ZipFile('123.zip', 'w')
newzip.write('a4.txt', compress_type=zipfile.ZIP_DEFLATED)
newzip.close()
#追加文件,a是追加
newzip = zipfile.ZipFile('123.zip', 'a')
newzip.write('a5.txt', compress_type=zipfile.ZIP_DEFLATED)
newzip.close()
3、压缩目录及子文件
import zipfile, os
#压缩目录
dirpath = 'Z:\\script\\python\\tmp\\000'
dirzip = zipfile.ZipFile('0.zip', 'w', zipfile.ZIP_DEFLATED)
for path,dirnames,filenames in os.walk(dirpath) :
fpath = path.replace(dirpath, '')
for filename in filenames :
dirzip.write(os.path.join(path,filename), os.path.join(fpath, filename))
dirzip.close()
4、解压缩
import os
import zipfile
filename = zipfile.ZipFile('abc.zip')
#读取压缩文件
print(filename.namelist())
#将压缩文件全部解压
filename.extractall()
#解压指定的某一个文件到当前目录,extract方法的第二个参数是将文件解压到哪个目录,默认是当前目录
filename.extract('abc/aaa')
filename.close()
代码大概这个样子,详细的自己测试吧