extractall

Python zipfile模块官网

正常使用:

解压缩: ZipFile.extract(member,path = None,pwd = None )

参数

解释

members

zipfile 对象中某个文件名

path

解压到的目的路径,默认是压缩包所在路径

pwd

压缩包密码, 默认无密码

例子

import zipfile
...
zip_file = zipfile.ZipFile(file_name, 'r')
try:
for names in zip_file.namelist():
zip_file.extract(names, path=mypath)
except Exception as e:
raise

压缩: 利用 write 方法, ZipFile.write(filename, arcname=None, compress_type=None)

参数

解释

filename

文件名

arcname

压缩文件名

compress_type

If given, compress_type overrides the value given for the compression parameter to the constructor for the new entry. 如果给定,compress_type将为新条目覆盖为压缩参数给构造函数指定的值。没用过不知道啥用。

注意: ZIP文件没有官方文件名编码。如果你有unicode文件名,你必须在将它们传递给你所需的编码之前将它们转换为字节串write()。WinZip将所有文件名解释为在CP437中编码,也称为DOS Latin。

注意: 档案名称应该与档案根目录相关,也就是说,它们不应该以路径分隔符开头。

注意: 如果arcname(或者filename如果arcname未给出)包含空字节,则归档文件的名称将在空字节处截断。

例子

def get_zip(filename, target_list, to_path=current_dir):
"""
zip file
:param filename: 压缩包命名
:param target_list: [(带压缩文件绝对路径,压缩后文件起名(相对路径)),....] 列表
:param to_path: 压缩包保存路径
:return: get_zip('SDA-ST-2000',
[[('/Users/sunping/avlsdk3/0ecccee29a1a47afbb09cba842f79ca2','License.alf'),
('/Users/sunping/avlsdk3/b92272762514429392a6d2fe8cd696f4','.DS_Store'),
('/Users/sunping/avlsdk3/9acd9ead7b4b4ebdb0b59288d9d08368','AVLSDK.so'),
('/Users/sunping/avlsdk3/38c4785d6fac4988bb256bc8b29e23d3','AVLscanner.exe'),
('/Users/sunping/avlsdk3/eff46ac936374111b9224e81c1a39bef','aid2name.so')], '/Users/sunping/antiy/client')
"""
z = zipfile.ZipFile(path_join(to_path, filename+'.zip'), 'w')
for t, s in target_list:
z.write(t, s)
z.close()

解决解压中文文件名报错

抛出异常: Illegal byte sequence, ‘ascii’ codec can’t decode byte … in position ……. 等等 诸如此类的错误,其实都是编码问题!!!

思路1: 直接读取/打开压缩包内文件, 利用 open 写入指定文件

注意: 这里不能使用 zipfile 对象的 namelist() 方法, 采用遍历 zipfile 对象的 infolist() 方法

代码举例

import sys
import shutil
import zipfile
...
zip_file = zipfile.ZipFile(file_name, 'r')
try:
for file_info in zip_file.infolist():
filename = unicode(file_info.filename, 'gb2312').encode("utf8") # 采用什么编码就用什么解码,再用 utf8 编码
# filename = file_info.encode('gb2312').decode('utf-8') # 也可以写成这样
print 'filename is ', filename
output_filename = os.path.join(name, filename)
output_file_dir = os.path.dirname(output_filename)
if not os.path.exists(output_file_dir):
os.makedirs(output_file_dir)
with open(output_filename, 'wb') as f:
shutil.copyfileobj(zip_file.open(file_info.filename), f)
except Exception as e:
Logger(sys.exc_info()[2]).ERROR(e)

可以省略指定解压文件对象

import zipfile
...
zip_file = zipfile.ZipFile(file_name, 'r')
global zip_file
yourpath = '/xxx/xxxx/xxxx...'
try:
zip_file.extractall(path=yourpath)
except Exception as e:
Logger(sys.exc_info()[2]).error(e)
finally:
zip_file.close
补充
python2.7. zipfile 中 处理文件名 :
def _encodeFilenameFlags(self):
if isinstance(self.filename, unicode):
try:
return self.filename.encode('ascii'), self.flag_bits
except UnicodeEncodeError:
return self.filename.encode('utf-8'), self.flag_bits | 0x800
else:
return self.filename, self.flag_bits
def _decodeFilename(self):
if self.flag_bits & 0x800:
return self.filename.decode('utf-8')
else:
return self.filename
python 3.6 zipfile 中 处理文件名:
# 编码
if flags & 0x800:
# UTF-8 file names extension
filename = filename.decode('utf-8')
else:
# Historical ZIP filename encoding
filename = filename.decode('cp437')
# 解码
if zinfo.flag_bits & 0x800:
# UTF-8 filename
fname_str = fname.decode("utf-8")
else:
fname_str = fname.decode("cp437")

由此看来, 上面这种解决办法只是另辟蹊径, 等待 python 官方修改这个 bug 吧

欢迎入群(^__^) :556993881 就差你啦啦啦啦

参考:

Stack Overflow python zipfile 无效文件名

Python标准库 » 13.数据压缩和存档 zipfile

相关阅读

ExtractFileDir 与 ExtractFilePath 的区别ExtractFileDir 从文件名中获取目录名(文件不在根目录下时取得的值后没有“/”,在根目

extract()经常使用来切片(脱壳)从一个对象中得到list下面是scrapy的官方文档,里面有选择器(selector)的一些介绍http://scrapy-chs.rea

Series.str.extract(pat, flags=0, expand=None)

参数: pat : 字符串或正则表达式 flags : 整型, expand : 布尔型,是否返回数据

dnf Extractor下完后直接安装就行,在这个界面有4个东西,修改DNF只需要安装DNF Extractor就足够了,其他3个是其他游戏的修改软件,装不