python2.7 handles Chinese characters garbled under win10

Reprinted: http://blog.csdn.net/mindmb/article/details/7898528


Engaged in a day, depressed for a day, and finally get this problem.

I have been thinking about changing the system back to Ubuntu countless times, but after thinking about it, I am not willing to admit it.


Facts have proved that there is no insurmountable hurdle.

First the example.

#coding=utf-8
import them
w='can'
os.makedirs(u'C:/Users/LiAng/Documents/你好/%s' %w)

At this time, an error will be reported:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)

The workaround is as follows:

#coding=utf-8
import them
import sys
reload(sys)
sys.setdefaultencoding('utf8')

w='can'
os.makedirs(u'C:/Users/LiAng/Documents/你好/%s' %w)

The Chinese folder was successfully created.

The u before the path is to convert the path to unicode, and these three important lines are:

import sys
reload(sys)
sys.setdefaultencoding('utf8')

Hope to help everyone.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326057184&siteId=291194637