unicode error preventing creation of text file

2020-04-22 02:30发布

问题:

What is causing this error and how can I fix it?

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

I have also tried reading different files in the same directory an get this same unicode error as well.

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

回答1:

You should escape backslashes inside the string literal. Compare:

>>> 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


回答2:

\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'