Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...