Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

python - SyntaxError when trying to use backslash for Windows file path

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

os.path.isfile()

But I noticed if back slash is used by copy&paste from Windows OS:

os.path.isfile("C:UsersxxxDesktopxxx")

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

When forward slash is used:

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

It worked.

Can I please ask why this happened? Even the answer is as simple as :"It is a convention."

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Backslash is the escape symbol. This should work:

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

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

"C:UsersxxxDesktopxxx"

But it's better practice and ensures cross-platform compatibility to collect your path segments (perhaps conditionally, based on the platform) like this and use os.path.join

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

Should return True for your case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...