SyntaxError when trying to use backslash for Windows file path

Question:

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

Asked By: Yu Zhang

||

Answers:

You get the problem with the 2 character sequences x and U — which are python escape codes. They tell python to interpret the data that comes after them in a special way (The former inserts bytes and the latter unicode). You can get around it by using a “raw” string:

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

or by using forward slashes (as, IIRC, windows will accept either one).

Answered By: mgilson

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.

Because backslashes are escapes in Python. Specifically, you get a Unicode error because the U escape means “Unicode character here; next 8 characters are a 32-bit hexadecimal codepoint.”

If you use a raw string, which treats backslashes as themselves, it should work:

os.path.isfile(r"C:UsersxxxDesktopxxx")
Answered By: Mike DeSimone
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.