我试图打开一个文件,我刚刚意识到py对我的用户名有问题(它是俄语)。有什么建议,如何正确地解码/编码这使闲置愉快?在
我用的是py2.6.5
xmlfile = open(u"D:\\Users\\Эрик\\Downloads\\temp.xml", "r")
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
xmlfile = open(str(u"D:\\Users\\Эрик\\Downloads\\temp.xml"), "r")
UnicodeEncodeError: 'ascii' codec can't encode characters in position 9-12: ordinal not in range(128)
在os.sys.getfilesystemencoding操作系统() “mbcs”
xmlfile=open(u“D:\Users\Эрик\下载\临时xml“.encode(“mbcs”),“r”)
回溯(最近一次呼叫): 文件“”,第1行,输入 xmlfile=open(u“D:\Users\Эрик\下载\临时xml“.encode(“mbcs”),“r”) IOError:[Errno 22]无效的模式(“r”)或文件名:“D:\Users\Y?”?ee\下载\临时xml'
第一个问题:
第二个问题:
}
^{pr2}$os.sys.getfilesystemencoding()
产生{有关在Windows中硬编码文件名的一般建议,按优先顺序降序排列:
(1)不要
(2) 使用
/
例如"c:/temp.xml"
(3) 使用带反斜杠的原始字符串
r"c:\temp.xml"
(4) 使用双反斜杠
"c:\\temp.xml"
第一个问题是解析器试图解释字符串中的反斜杠,除非使用
r"raw quote"
前缀。在2.6.5中,不需要特别处理Unicode字符串,但可能需要在源代码中使用文件编码声明,如:如PEP 263中所定义。下面是一个交互工作的示例:
^{pr2}$是的,这是在Unix系统上,所以
\
没有意义,我的终端编码是utf-8,但它可以工作。您只需要在解析器读取文件时向它提供编码提示。在相关问题 更多 >
编程相关推荐