编码损坏的 IOError return 消息

IOError return message with broken encoding

Python 2.6 Linux(中央操作系统)

我使用 shutil.copyfile() 函数复制文件。如果文件不存在,我会在日志文件中写一条异常消息。所以,我收到带有错误符号的消息,因为我的文件路径包含俄语字符。例如: 原始文件路径 - “/PNG/401/405/018_/01200Γ/osv_1.JPG”('Γ 是俄语符号) 消息中的文件路径 - “/PNG/401/405/018_/01200\xd0\x93/osv_1.JPG” 我尝试使用此代码 print(str(error).decode('utf-8')) 但它不起作用。但是这段代码 print(os.listdir(r'/PNG/401/405/018_/')[0].decode('utf-8')) 工作得很好。有任何想法吗?

让我们分解你的命令:

print(str(error).decode('utf-8'))

首先它会做:

str(error)

把它变成一个字符串让我们称之为 temp_string

然后它会尝试做:

temp_string.decode('utf-8)

这将作为字符串对象失败,没有 .decode(),因此您将收到如下错误消息:

builtins.AttributeError: 'str' object has no attribute 'decode'

它永远不会到达 print()

你应该做的是:

print(error.decode('utf-8'))

或者,您可以使用:

print(str(error))

嗯,输出是完全正确的。 'Г' 是 unicode 字符 U+0413(西里尔大写字母 GHE),它的 UTF-8 编码是 '\xd0''\x93' 这两个字符。您只需使用支持 utf8 的文本编辑器(gvim 或 notepad++)读取日志文件,或者如果您必须在 Python 中处理它,请确保将其作为 utf8 编码文件读取。

print(str(error).decode('string-escape')) - 适合我