Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:\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."

like image 441
Yu Zhang Avatar asked Sep 09 '14 02:09

Yu Zhang


People also ask

Is it possible to use backslash for Windows path in Python?

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:

Does c:\windows\ have a backslash?

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.

Can I use a raw string for backslash?

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).

What is the difference between a forward slash and a backslash?

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.


1 Answers

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.

like image 124
Russia Must Remove Putin Avatar answered Oct 04 '22 12:10

Russia Must Remove Putin