編碼的世界 / 優質文選 / 財富

python2.7在win10下中文漢字亂碼處理


2022年5月18日
-   

轉載:http://blog.csdn.net/mindmb/article/details/7898528
搞了一天,鬱悶了一天,終於把這個問題搞定了。
無數次地在想把系統換回ubuntu,但想了想又不甘心認慫。
事實證明,沒有過不去的坎。
首先上例子。
#coding=utf-8
import os
w='可以'
os.makedirs(u'C:/Users/LiAng/Documents/你好/%s' %w)

這時會報錯:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)

解決方法如下:
#coding=utf-8
import os
import sys
reload(sys)
sys.setdefaultencoding('utf8')
w='可以'
os.makedirs(u'C:/Users/LiAng/Documents/你好/%s' %w)

成功創建中文文件夾。
其中路徑前的u是把路徑轉換成unicode,裏面重要的這三行:
import sys
reload(sys)
sys.setdefaultencoding('utf8')

希望能幫助到大家。

熱門文章