zip包中中文名解压是出现乱码的核心是文件名编码格式不正确。
官方释疑:
There is no official file name encoding for ZIP files. If you have unicode file names, you must convert them to byte strings in your desired encoding before passing them to write(). WinZip interprets all file names as encoded in CP437, also known as DOS Latin.
zip包文件名会用CP437来编码,因此需要相应的编解码操作来避免乱码。因此不用ZipFile.extract(member[, path[, pwd]]),需用shutil进行数据内容的拷贝,这样就解决了压缩包下中文多路径解压乱码问题。
实现代码如下:
import zipfile
import shutil
def unzip_each_zip_package(fn):
try:
if zipfile.is_zipfile(fn):
zf = zipfile.ZipFile(fn)
for fName in zf.namelist():
correct_fn = fName.encode('cp437').decode('gbk') #这里就用来编解码的操作的
if not os.path.exists(correct_fn) and str(correct_fn).endswith("/"): #判断文件路径是否存在
os.makedirs(correct_fn) #没有文件路径的创建文件路径
else:
with open(right_fn, 'wb') as disfile: #创建相应文件
with zf.open(fName, 'r') as srcfile:
shutil.copyfileobj(srcfile, disfile)
except Exception as error:
print(error)
本文介绍了解决zip压缩包在解压时中文文件名出现乱码的问题,核心在于正确的文件名编码格式。文章解释了zip包使用CP437编码,以及如何通过编解码操作避免乱码,提供了具体实现代码。
1094

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



