python定義文件路徑報錯

python執行的命令很簡單,如下:

>>> path='C:\Users\Roger\Desktop\spider\qfmc.jpg'

接着遇到報錯:SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

 

經過查找資料,發現是由於python路徑中的轉義字符導致的,解決方法如下3種:

1、在路徑前面加r,即保持字符原始值的意思。

>>> path=r'C:\Users\Roger\Desktop\spider\qfmc.jpg'


2、替換爲雙反斜槓

path='C:\\Users\\Roger\\Desktop\\spider\\qfmc.jpg'


3、替換爲正斜槓

>>> path='C:/Users/Roger/Desktop/spider/qfmc.jpg'

原文鏈接:https://blog.csdn.net/xd060606/article/details/87164798

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章