使用以下行:
>>> file = open('C:\Users\mihir\Documents\test.txt')
我收到此错误:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape
关于我为什么收到该消息的任何想法?
反斜杠用于在字符串中形成转义序列。始终避开它们,或在路径中使用正斜杠。
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')
反斜杠被视为跳过空格,因此您应该为此使用原始字符串。尝试:
file = open(r'C:\Users\mihir\Documents\test.txt')
它应该工作。谢谢