1

是什么导致了这个错误,我该如何解决?

(unicode 错误)“unicodeescape”编解码器无法解码位置 2-3 中的字节:截断 \UXXXXXXXX 转义

我还尝试在同一目录中读取不同的文件,并得到同样的 unicode 错误。

file1 = open("C:\Users\Cameron\Desktop\newtextdocument.txt", "w")
for i in range(1000000):
    file1.write(str(i) + "\n")
4

2 回答 2

1

\U is being treated as the start of a Unicode literal. Use a raw string (a preceding r) to prevent this translation:

>>> 'C:\Users'
  File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
>>> r'C:\Users'
'C:\\Users'
于 2013-11-06T04:38:04.667 回答
1

您应该在字符串文字中转义反斜杠。相比:

>>> print("\U00000023")  # single character
#
>>> print(r"\U00000023") # raw-string literal with 
\U00000023
>>> print("\\U00000023") # 10 characters
\U00000023

>>> print("a\nb")  # three characters (literal newline)
a
b
>>> print(r"a\nb") # four characters (note: `r""` prefix)
a\nb
于 2013-11-06T03:52:50.320 回答