https://my.oschina.net/mcyang000/blog/289460 Open the path contains Chinese files, note: 1 in the Windows file name encoding is encoded with GBK and so on to save, so to decode the file path first, in the GBK code: String-Decoding to unicode--encoding (note the conversion of STR and Unicode)
With open (r "d:\ My Documents \ Desktop \python\config.ini". Decode (' UTF8 '). Encode (' GBK '), ' RB ') as F:
Print F.read ()
Or use #coding=utf-8 #当然这里要在前面设置系统的编码方式with open (ur "d:\ My Documents \ Desktop \python\config.ini". Encode (' GBK '), ' RB ') as F: or with open (Ur "D:\ My Documents \ Desktop \python\config.ini", ' RB ') as F: Abstract: In Windows use GBX (gb2312,gbk,gb18030 I do not know which one) to encode the file name and the path to save. Opening a file with functions such as open (Filename.encode (' GBK ')) can be a good solution. In addition the path delimiter to write Unix-style '/', do not write ' \ '
Windows uses GBX (gb2312,gbk,gb18030 I don't know which) to encode the file name and path. Opening a file with functions such as open (Filename.encode (' GBK ')) can be a good solution.
#coding:utf8if __name__ == ‘__main__‘: srcfile = r"D:/测试路径/测试文件.txt" f = open(srcfile.decode(‘utf8‘).encode(‘gbk‘)) for text in f.readlines(): print text.decode(‘gbk‘) f.close()
Or:
#coding:utf8if __name__ == ‘__main__‘: srcfile = u"D:/测试路径/测试文件.txt" f = open(srcfile.encode(‘gbk‘)) for text in f.readlines(): print text.decode(‘gbk‘) f.close()
Both of these methods are available.
In addition, do not be disturbed by this sentence:
print text.decode(‘gbk‘)
It only means that the contents of the file are encoded with GBK. More content Visible http://my.oschina.net/iuranus/blog/262914
Note: This can also be opened in this case:
u"D:/测试路径/测试文件.txt" f = open(srcfile)
However, when using the OpenCV Library, Cv2.imread (srcfile), the srcfile must be GBK encoded (srcfile.encode (' GBK ')) to open, but also pay attention to the Unix-style '/', rather than ' \ '.
[Python io Learning article] [Open file containing Chinese path]