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:\Users\xxx\Desktop\xxx")
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."
Plus one from me. It is better to use forward slashes for a Windows path in Python anyway. Backslash is the escape symbol. This should work: This works because you escape the escape symbol, and Python passes it as this literal:
Have you ever noticed that it’s C:\Windows\ in Windows, http://howtogeek.com/ on the web, and /home/user/ on Linux, OS X, and Android? Windows uses backslashes for paths, while everything else seems to use forward slashes.
Using a raw string usually works fine, still you have to note that r""" escapes the quoute char. That is, raw string is not absolutely raw and thats the reason why you cant use backslash (or any odd number of backslashes) in the end of a string like '\' (the backslash would escape the following quote character).
A typical Windows user sees a forward slash when they type a web address and a backslash when they type the location of a local folder, so this can be confusing. Websites follow the Unix convention, as do other protocols like FTP.
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:\Users\xxx\Desktop\xxx"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With