读取、创建、解压压缩包 中文乱码问题解决方式

读取压缩包

读取压缩包(zip)内文件,主要使用zipfile.ZipFile():

import zipfile
with zipfile.ZipFile('C:\\Users\\Administrator\\Desktop\\bt.zip','r') as zipobj:
    print(zipobj.namelist())

压缩包存在中文会出现乱码,尽量不要出现中文,也可以调整编码:

import zipfile
with zipfile.ZipFile('C:\\Users\\Administrator\\Desktop\\bt.zip','r') as zipobj:
    for file_name in zipobj.namelist():
        print(file_name.encode('cp437').decode('gbk'))

读取压缩包内文件信息:

import zipfile
with zipfile.ZipFile('C:\\Users\\Administrator\\Desktop\\bt.zip','r') as zipobj:
    for file_name in zipobj.namelist():
        info=zipobj.getinfo(file_name)
        new_file=file_name.encode('cp437').decode('gbk')
        print(new_file,info)

# Components/avcodec-56.dll <ZipInfo filename='bt.rar/YouTube Downloader Pro/Components/avcodec-56.dll' compress_type=deflate external_attr=0x20 file_size=20348430 compress_size=7733031>

也可以打印info.file_size(文件大小),info.compress_size(压缩后大小),输出单位只字节

解压压缩包

使用zipobj.extract(压缩包内要解压的文件名,解压到哪个位置),只能解压单个文件夹,没什么卵用:

import zipfile
with zipfile.ZipFile('C:\\Users\\Administrator\\Desktop\\bt.zip','r') as zipobj:
    zipobj.extract('YouTube Downloader Pro/')

中文乱码解决方法

如果压缩包中出现中文,解压读取都会出现乱码,所以建议路径不要包含中文。如果有中文可以现货去正确的编码文字,在重命名:

import zipfile
with zipfile.ZipFile('C:\\Users\\Administrator\\Desktop\\bt.zip','r') as zipobj:
    for file_name in zipobj.namelist():
        info=zipobj.getinfo(file_name)
        new_file=file_name.encode('cp437').decode('gbk')
        print(new_file,info)

使用zipobj.extractall(path=解压到哪个位置),解压到当前目录下:

import zipfile
with zipfile.ZipFile('C:\\Users\\Administrator\\Desktop\\bt.zip','r') as zipobj:
    zipobj.extractall('./')

对于有密码的压缩包,可以设置zipobj.extractall(path=解压到哪个位置,pwd=b’密码’)

import zipfile
with zipfile.ZipFile('C:\\Users\\Administrator\\Desktop\\bt.zip','r') as zipobj:
    zipobj.extractall('./',pwd=b'123')

创建压缩包

使用zipobj.write(待压缩文件名),添加的文件必须存在,否则报错:

import zipfile
file_list=['bobo.py','file.py','rosi.json']
with zipfile.ZipFile('创建压缩包.zip','w') as zipobj:
    for file in file_list:
        zipobj.write(file)

向已有的压缩包内添加文件

import zipfile
with zipfile.ZipFile('创建压缩包.zip','a') as zipobj:
    zipobj.write('server.py')

注意文件的打开方式及中文乱码问题。

发表评论