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


Python運行后,報錯:SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

原因:window 讀取文件可以用\,但是在字符串中\是被當作轉義字符來使用,經過轉義之后可能就找不到路徑的資源了,例如\t會轉義為tab鍵

 

上代碼:

>>> def func1(path_name):
...     import os
...     if os.path.exists(path_name):
...         return "True"
...     else:
...         return "False"
...
>>> func1("C:\Users\renyc")#會報錯
  File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
>>>
本例中:"C:\Users\renyc"經過轉義之后就找不到路徑的資源了。

解決方法:

>>> def func1(path_name):
...     import os
...     if os.path.exists(path_name):
...         return "True"
...     else:
...         return "False"
...
>>> func1(r"C:\Users\renyc")#加上r,聲明字符串,不用轉義處理
'True'
>>> func1("C:\\Users\\renyc")#絕對路徑的處理
'True'
>>>

總結有三種方法:

一:更換為絕對路徑的寫法
func1("C:\\Users\\renyc")

二:顯式聲明字符串不用轉義(加r)
func1(r"C:\Users\renyc")

三:使用Linux的路徑/
func1("C:/Users/renyc")



 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM