0

使用以下行:

>>> file = open('C:\Users\mihir\Documents\test.txt')

我收到此错误:

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

关于我为什么收到该消息的任何想法?

4

2 回答 2

4

反斜杠用于在字符串中形成转义序列。始终避开它们,或在路径中使用正斜杠。

file = open('C:\\Users\\mihir\\Documents\\test.txt')
file = open(r'C:\Users\mihir\Documents\test.txt')
file = open('C:/Users/mihir/Documents/test.txt')
于 2012-12-25T08:45:09.080 回答
1

反斜杠被视为跳过空格,因此您应该为此使用原始字符串。尝试:

file = open(r'C:\Users\mihir\Documents\test.txt')

它应该工作。谢谢

于 2012-12-25T10:47:47.127 回答