读取压缩包
读取压缩包内文件
语法:
with zipfile.ZipFile('zipfile_name','r') as zipobj:
print(zipobj.namelist())
import zipfile
# 读取上层文件夹中的demo.zip压缩包
with zipfile.ZipFile('../demo.zip','r') as zipobj:
print(zipobj.namelist())
'''
输出结果
['demo/', 'demo/demo.txt', 'demo/test.py', 'demo/测试/', 'demo/测试.txt']
'''
有些时候,如果文件的命令或路径中存在中文,解压的时候会出现乱码,这时候就需要对编码和解码进行处理
import zipfile
with zipfile.ZipFile('../demo.zip','r') as zipobj:
for filename in zipobj.namelist():
print(filename.encode('cp936').decode('gbk'))
# GBK的code page是CP936
对于gbk、utf-8格式的编码和解码,可以查看该篇文章进行拓展了解
读取压缩包内文件信息
语法:
zipobj.getinfo(filename)
file_size 文件大小
compress_size 压缩后的文件大小
import zipfile
with zipfile.ZipFile('../demo.zip','r') as zipobj:
for filename in zipobj.namelist():
file_name = filename.encode('cp936').decode('gbk')
file_info = zipobj.getinfo(filename)
print(file_name,file_info.file_size,file_info.compress_size)
'''
输出结果:
demo/ 0 0
demo/demo.txt 4129 717
demo/test.py 92 92
demo/测试/ 0 0
demo/测试.txt 0 0
'''
解压压缩包
将压缩包内单个文件解压出来
语法:
with zipfile.ZipFile('zipfile','r') as zipobj:
zipobj.extract('filename','path')
zipfile 压缩包名称
filename 压缩包内要解压的文件名称
path 解压到的文件夹路径
import zipfile
with zipfile.ZipFile('../demo.zip','r') as zipobj:
zipobj.extract('demo/demo.txt','/media/bobo/测试/')
注意:如果压缩包内解压的文件在某个文件夹下,需要将标明文件所在的路径,否则会因找不到文件而报错
而解压该文件的时候,会将文件夹一并解压
处理压缩包里的中文
如果文件的命令或路径中存在中文,解压的时候会出现乱码,需要进行调整编码
建议路径中文件夹和文件不要出现中文命名,如果出现中文,需要先获取正确的编码文字,再重命名
import zipfile
with zipfile.ZipFile('../demo.zip','r') as zipobj:
# print(zipobj.namelist())
# 输出结果是一个列表
# ['demo/', 'demo/demo.txt', 'demo/test.py', 'demo/测试/', 'demo/测试.txt']
file_list = zipobj.namelist()
# 通过取列表中下标元素的方式选取要解压的文件
choose_file = file_list[2].encode('cp936').decode('gbk')
zipobj.extract(choose_file,'/media/bobo/测试/')
将压缩包内所有文件都提取出来
语法
with zipfile.ZipFile('zipfile','r') as zipobj:
zipobj.extractall('path')
zipfile 压缩包名称
path 解压到的文件夹路径
import zipfile
with zipfile.ZipFile('../demo.zip','r') as zipobj:
zipobj.extractall('/media/bobo/test/')
将有密码的压缩包解压
with zipfile.ZipFile('zipfile','r') as zipobj:
zipobj.extractall(path=’dir’,pwd=b'password')
zipfile 压缩包名称
path 解压到的文件夹路径
pwd 密码
import zipfile
with zipfile.ZipFile('./pwdfile.zip','r') as zipobj:
zipobj.extractall(path='/media/bobo/Python/',pwd=b'123456')
创建压缩包
创建压缩包文件
语法
filelist = [file1,file2...]
with zipfile.ZipFile('zipfile','w') as zipobj:
for file in filelist:
zipobj.write(file)
w 意为写入
filelist = ['/media/bobo/zipOperation1.py','/media/bobo/demo/demo.txt']
with zipfile.ZipFile('test.zip','w') as zipobj:
for file in filelist:
zipobj.write(file)
向已有压缩包内添加文件
语法
with zipfile.ZipFile('zipfile','a') as zipobj:
zipobj.write(new_file)
a 意为追加
import zipfile
with zipfile.ZipFile('./test.zip','a') as zipobj:
zipobj.write('/media/bobo/zipOperation6.py')