SyntaxError when trying to use backslash for path to Windows file

I tried to confirm if the file exists using the following line of code:

os.path.isfile()

But I noticed that if the slash uses copy and paste from Windows:

os.path.isfile("C:\Users\xxx\Desktop\xxx")

I got a syntax error: (unicode error) etc. etc. etc.

When using a slash:

os.path.isfile("C:/Users/xxx/Desktop/xxx")

It worked.

May I ask why this happened? Even the answer is as simple as: "This is an agreement."

+4
source share
3 answers

The backslash is the escape character. This should work:

os.path.isfile("C:\\Users\\xxx\\Desktop\\xxx")

This works because you avoid the escape character, and Python passes it as this literal:

"C:\Users\xxx\Desktop\xxx"

- (, , ), , os.path.join

path_segments = ['/', 'Users', 'xxx', 'Desktop', 'xxx']
os.path.isfile(os.path.join(*path_segments))

True .

+5

- escape- Python. , Unicode error, \U escape Unicode , 8 - 32- .

, , :

os.path.isfile(r"C:\Users\xxx\Desktop\xxx")
+4

2 \x \U - escape- python. python , ( ). , "" :

os.path.isfile(r"C:\Users\xxx\Desktop\xxx")

(, IIRC, ).

+3
source

All Articles