在Python 2.7上,
for dir in os.listdir("E:/Library/Documents/Old - Archives/Case"):
print dir打印输出:
Danny.xlsx
Dannyh.xlsx
~$??? ?? ?????? ??? ???? ???????.docx而这一点:
# using a unicode literal
for dir in os.listdir(u"E:/Library/Documents/Old - Archives/Case"):
print dir打印输出:
Dan.xlsx
Dann.xlsx
Traceback (most recent call last):
File "E:\...\FirstModule.py", line 31, in <module>
print dir
File "C:\Python27\lib\encodings\cp1252.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_table)
UnicodeEncodeError: 'charmap' codec can't encode characters in position 2-4: character maps to <undefined>该文件的名称使用希伯来语,如下所示:המסמך.xls
我如何让它在Python中也出现在希伯来语中?
发布于 2012-05-07 19:58:05
解决了它:文档顶部的# -*- coding: utf-8 -*-解决了它。
发布于 2012-03-31 22:34:22
带有u''字符串文字的版本工作得很好:使用Unicode路径名询问,您将得到一个Unicode路径名作为响应,允许您处理包含当前代码页之外的字符的文件名。
您的问题完全来自于尝试对文件名执行print操作。将Unicode输出到Windows命令提示符是一种尝试。
默认的C标准库打印函数仅限于区域设置代码页。除非您直接调用Unicode函数WriteConsoleW (使用ctype),否则您永远不会获得可靠的控制台Unicode支持;即使这样,它也不会工作,除非选择合适的非默认字体。这影响了几乎所有的非本机命令行工具,而不仅仅是Python。
发布于 2012-04-01 01:10:46
问题是您的输出控制台对每个错误消息都使用cp1252编码,而希伯来语不能在该编码下打印。使用支持UTF8的集成开发环境和支持希伯来语的集成开发环境中的字体,当使用带有Unicode路径的os.listdir时,它将正常工作。
下面是一个来自PythonWin集成开发环境的示例,其中包含和不包含Unicode路径。
PythonWin 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32.
Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information.
>>> import os
>>> for f in os.listdir('.'):
... print f
...
x.exe
x.py
x.pyc
y.py
?????.xls
>>> for f in os.listdir(u'.'):
... print f
...
x.exe
x.py
x.pyc
y.py
המסמך.xls还要注意,源文件中的编码声明对生成输出没有任何作用。它只声明保存源文件的编码,这会影响在源文件中写入非ASCII字符的能力。
https://stackoverflow.com/questions/9954948
复制相似问题