玩蛇网提供最新Python编程技术信息以及Python资源下载!

Python字符编码不能完全转换想问下为什么

是这样的,文件从mac端传到windows端会导致文件名(中文)乱码。于是我想写个python脚本来改下文件名的编码,代码如下:

pythondef convert_gbk_to_utf8():
    for file in os.listdir(ROOT_PATH):
        new_file = file.encode("gbk", "ignore").decode("utf-8", "ignore")
        os.renames(os.path.join(ROOT_PATH, file), os.path.join(ROOT_PATH, new_file))

结果差强人意,有部分文件名转化的不完整。想问下为什么?

乱码的文件名

鏁堟灉鍥_K11.1_璐圭敤鏄庣粏_鏈彁浜よ璐_.png
鏁堟灉鍥_K11.2_璐圭敤鏄庣粏_濉啓璺ˉ璐_png

调用os.listdir()打印出来的文件名

def convert_gbk_to_utf8():
for file in os.listdir(ROOT_PATH):
new_file = file.encode("gbk", "ignore").decode("utf-8", "ignore")
os.renames(os.path.join(ROOT_PATH, file), os.path.join(ROOT_PATH, new_file))

看题意,楼主应该是想让编码方式从gbk 转为utf8 在Python中 如果想从一种编码方式转向另一种编码方式 是以unicode 作为中间码的 将某种编码方式转为unicode码 用的是decode而不是encode。encode 是将unicode码转为一种具体的编码方式 所以楼主上述代码中 new_file = file.encode("gbk", "ignore").decode("utf-8", "ignore") 这一句变为 new_file = file.decode("gbk", "ignore").encode("utf-8", "ignore")应该就行了

原文件名不是 gbk 编码的吧?试试 gb18030

参考:Chinese in Mac OS X 10.7 Lion

似乎有奇怪的字符混进来了:

>>> xsel | iconv -t gb18030
效果K11.1_费用明细_未提交计.png
效果K11.2_费用明细_填写路桥png

看上去没问题,但是在 Vim 中查看时发现:

不要使用 errors='ignore',除非你很明确地知道并且想要这么做。

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/wenda/wd18798.html

相关文章 Recommend

玩蛇网Python互助QQ群,欢迎加入-->: 106381465 玩蛇网Python新手群
修订日期:2017年05月31日 - 14时31分37秒 发布自玩蛇网

您现在的位置: 玩蛇网首页 > Python问题解答 > 正文内容
我要分享到:

必知PYTHON教程 Must Know PYTHON Tutorials

必知PYTHON模块 Must Know PYTHON Modules