python中zipfile文件名编码的问题
在python中编程导入压缩包,利用zipfile包,从zipinfo读取文件名总是出错,创建的文件名是乱码,写入pgsql更是出错。
但在ubuntu下测试却正常,在windows下测试总是失败。
if not hdfs.exists_file_dir(dir): hdfs.make_dir(dir) hdfs.create_file(hpath, zip.read(info)) # 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(). origin_name = os.path.split(info.filename)[-1].decode(chardet.detect(info.filename)['encoding']) df = DataPart( id=part_id, data_title=origin_name, data_title_en=origin_name, data_author=data_author, data_name=hpath, origin_file_name=origin_name, remark=remark if remark else 'extracted', store_type='file', file_size=info.file_size, file_ext=file_ext ) db.session.add(df) db.session.commit()
初步分析应该是zipfile中的文件名不是unicode编码,将其进行unicode编码应该可以解决。
在zipfile的文档中,有这样一句话:
1 | Note 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. |
根据以上,先用chartdet进行文件名编码的判定,然后进行unicode解码,汉字文件名可以正常显示,写入数据库也正常了。
# 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(). origin_name = os.path.split(info.filename)[-1].decode(chardet.detect(info.filename)['encoding'])
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示