是这样的,文件从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()打印出来的文件名

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
原文件名不是 gbk 编码的吧?试试
gb18030。参考:Chinese in Mac OS X 10.7 Lion
似乎有奇怪的字符混进来了:
看上去没问题,但是在 Vim 中查看时发现:
不要使用
errors='ignore',除非你很明确地知道并且想要这么做。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")应该就行了