import os
for i in os.listdir("E:\Torchlight II"):
print i
代码很简单我们使用os的listdir函数遍历了E:\Torchlight II这个目录(Torchlight ?! :)),由于这个目录下有些文件是以中文命名的,所以在最后print结果时出现了乱码,像这样:
那么问题出在哪儿呢? 别急,我们一点一点来分析它。
从这里和这里我们几乎能够肯定的知道问题是出在:
This means that the python console app can't write the given character to the console's encoding.
More specifically, the python console app created a _io.TextIOWrapperd instance with an encoding that cannot represent the given character.
sys.stdout --> _io.TextIOWrapperd --> (your console)
看到这里不知你是否与我想的一样,能不能去设置console的编码,将其设置为能够理解中文字符的编码不就可以正常的显示出中文了吗?等等,让我们在多Google一会儿,
Python determines the encoding of stdout and stderr based on the value of the LC_CTYPE variable, but only if the stdout is a tty. So if I just output to the terminal, LC_CTYPE (or LC_ALL) define the encoding. However, when the output is piped to a file or to a different process, the encoding is not defined, and defaults to 7-bit ASCII.
更详细的说明如下:
1). When Python finds its output attached to a terminal, it sets the sys.stdout.encoding attribute to the terminal's encoding. The print statement's handler will automatically encode unicode arguments into str output.
2). When Python does not detect the desired character set of the output, it sets sys.stdout.encoding to None, and print will invoke the "ascii" codec.
嚯嚯,看来刚才的想法是可行的只是不太优雅罢了,因为我们得去修改系统的设置。事实上上面的论述是基于linux环境的,在linux下可能需要我们去更改某个环境变量的值(LC_CTYPE or LANG);如果我们是在windows下面的话,console的编码设置是跟操作系统的区域设置相关的。比如在中文的win7环境下,console默认的编码就是GBK(cp936)。你可以试试下面的代码:
import os
for i in os.listdir("E:\Torchlight II"):
print i.decode('gbk')
在代码中我们手动告诉了python对读入的字符串按章gbk编码来进行解码,而这一个动作之后数据已经是标准的unicode字符了,可以放心的交给print去打印输出了(即使这会儿sys.stdout.encoding = utf-8):
ps:
实际在google中还查到过很多相关的类似编码的问题,比如这里的,还有这里的。虽然问题的样子千变万化并且解决方式多种多样甚至是python自己的特定解决方式,比如这里。但这些问题本质都是一样的都是关于字符的编码和解码,搞清楚了其中的本质所有问题都能够迎刃而解。
给出几篇我认为有价值的参考资料:
http://docs.python.org/howto/unicode.html#history-of-character-codes Unicode HOWTO
http://farmdev.com/talks/unicode/ Unicode In Python, Completely Demystified
http://www.stereoplex.com/blog/python-unicode-and-unicodedecodeerror Python, Unicode and UnicodeDecodeError http://www.joelonsoftware.com/articles/Unicode.html The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets