读取压缩包内文件
import zipfile
with zipfile.ZipFile(‘压缩包.zip’,‘r’) as zip1:
print(zip1.namelist())
#文件名含有中文会出现乱码
处理压缩包内的中文
with zipfile.ZipFile(‘压缩包.zip’,‘r’) as zip2:
for file_name in zip2.namelist():
print(file_name.encode(‘cp437’).decode(‘gbk’))
读取压缩包内文件信息
with zipfile.ZipFile(‘压缩包.zip’,‘r’) as zip3:
for file_name in zip2.namelist():
info=zip3.getinfo(file_name)
new_filename=file_name.encode(‘cp437’).decode(‘gbk’)
print(new_filename,info.file_size,info.compress_size)
#compress_size为压缩后的文件大小
将压缩包内单个文件解压出来
with zipfile.ZipFile(‘压缩包.zip’,‘r’) as zip4:
zip4.extract(‘file.txt’) #zip.extract(文件名,解压位置),默认为目录位置
中文乱码解决方法(先获取正确的编码文字及乱码文字,再重命名)
with zipfile.ZipFile(‘压缩包.zip’,‘r’) as zip4:
zip4.extract(‘乱码.txt’)
将所有文件提取出来
with zipfile.ZipFile(‘压缩包.zip’,‘r’) as zip4:
zip4.extractall() #zip.extractall(path=‘解压位置’)
解压有密码的压缩包
with zipfile.ZipFile(‘有密码的压缩包.zip’,‘r’) as zip5:
zip5.extractall(path=‘解压位置’,pwd=b’解压密码’)
创建压缩包
file_list=[‘file1’,‘file2’]
with zipfile.ZipFile(‘压缩包.zip’,‘w’) as zip6:
for file in file_list:
zip6.write(file)
向已有压缩包添加文件
with zipfile.ZipFile(‘已有的压缩包.zip’,‘a’) as zip7:
zip7.write(‘file’)
学习链接:https://www.bilibili.com/video/BV197411f7Rp
这篇博客介绍了如何使用Python的zipfile模块来操作压缩包,包括读取压缩包内文件、处理中文文件名、读取文件信息、解压单个和所有文件、解压带密码的压缩包以及创建和向已有压缩包添加文件。通过示例代码展示了具体实现方法。
1674

被折叠的 条评论
为什么被折叠?



