5

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

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Yu Zhang
  • 2,037
  • 6
  • 28
  • 42

3 Answers3

6

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.

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
  • 2
    +1 for introducing me to the segmentation strategy. I don't use Python, but I imagine this strategy can apply to most languages. – Chris Cirefice Sep 10 '14 at 00:43
4

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:\Users\xxx\Desktop\xxx")
Mike DeSimone
  • 41,631
  • 10
  • 72
  • 96
  • 1
    Thank you very much, I was wondering why people are using a 'r' as part of argument. Now I now it is "raw string". – Yu Zhang Sep 09 '14 at 06:08
3

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:\Users\xxx\Desktop\xxx")

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

mgilson
  • 300,191
  • 65
  • 633
  • 696