写在前面
最近有很多项目需要用到zip解压,python自带了zipfile模块,但是文件带有中文名时会出现乱码,查找资料后发现zipfile中文件名使用了cp437的编码方式,使用utf8或者gbk重新解析一下即可。
实现
import zipfile
import os,shutil
def ziptest():
zip_file = zipfile.ZipFile('./test.zip')
DIR = './test_zip'
zip_list = zip_file.namelist()
if os.path.exists(DIR):
shutil.rmtree(DIR)
os.mkdir(DIR)
for f in zip_list:
try:
nf = f.encode('cp437').decode('gbk')
except:
nf = f.encode('utf-8').decode('utf-8')
new_path = os.path.join(DIR, nf)
# 判断f是否是目录,目录的结尾是'/'或'\'
if f[-1] not in ['\\','/']:
with open(new_path,'wb') as file:
file.write(zip_file.read(f))
file.close()
else:
os.mkdir(new_path)
zip_file.close()