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

"F:\program files (x86)\Python35\python.exe" "F:/program files (x86)/JetBrains/Selenium2/Elements/magua_duxiewenjian.py"
File "F:/program files (x86)/JetBrains/Selenium2/Elements/magua_duxiewenjian.py", line 3
file = open('C:\Users\guojian\Desktop\无锡梵天.doc')
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

错误原因:file = open('C:\Users\guojian\Desktop\无锡梵天.doc')这行代码中有几个“\”,而“\”在Python中表示转义.

解决方法:

(1)在字符串前加一个字母r,如下

file = open(r'C:\Users\guojian\Desktop\无锡梵天.doc')

这样可以告诉编译器这个string是个raw string,不要转义

 

(2)将字符串中反斜杠换成正斜杠,如下

file = open('C:/Users/guojian/Desktop/无锡梵天.doc')

 

(3)在字符串中单反斜杠换成双反斜杠,如下

file = open('C:\\Users\\guojian\\Desktop\\无锡梵天.doc')

 

posted @ 2017-08-21 14:49  Mr.Gavin  阅读(1121)  评论(0编辑  收藏  举报