unicode error preventing creation of text file

2020-04-22 01:57发布

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

2条回答
beautiful°
2楼-- · 2020-04-22 02:39

\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'
查看更多
姐就是有狂的资本
3楼-- · 2020-04-22 02:49

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
查看更多
登录 后发表回答