我有名为"SSE-Künden, SSE-Händler.pdf"的文件,其中有这两个unicode char ( ü,ä)当我在python解释器上打印这个文件名的时候,unicode值正在被转换成相应的ascii值,我猜是'SSE-K\x81nden, SSE-H\x84ndler.pdf',但我想
测试目录包含名为'SSE-Künden,SSE-Händler.pdf‘的pdf文件。
我尝试了一下:os.walk( path )中a,b,c的路径= 'C:\test‘:打印c
['SSE-K\x81nden, SSE-H\x84ndler.pdf']我如何转换这个ascii字符到它各自的unicode字符,我想在解释器上显示原始名称("SSE-Künden, SSE-Händler.pdf"),并在它is.how时写入一些文件,我做到了这一点。我使用的是Python2.6和windows操作系统。
谢谢。
发布于 2011-09-22 14:54:40
假设您的终端支持显示字符,遍历文件列表并单独打印它们(或者使用Python 3,它在列表中显示Unicode ):
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> for p,d,f in os.walk(u'.'):
... for n in f:
... print n
...
SSE-Künden, SSE-Händler.pdf还要注意,我使用的是Unicode字符串(u'.')作为路径。这将指示os.walk返回Unicode字符串,而不是字节字符串。在处理非ASCII文件名时,这是一个好主意。
在Python 3中,字符串默认为Unicode,非ASCII字符显示给用户,而不是显示为转义代码:
Python 3.2.1 (default, Jul 10 2011, 21:51:15) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> for p,d,f in os.walk('.'):
... print(f)
...
['SSE-Künden, SSE-Händler.pdf']发布于 2011-09-22 14:58:20
for a,b,c in os.walk(path):
for n in c:
print n.decode('utf-8')发布于 2011-09-22 14:54:50
用于写入文件:http://docs.python.org/howto/unicode.html#reading-and-writing-unicode-data
https://stackoverflow.com/questions/7510350
复制相似问题