4

When setting a string to a filepath in Python for WIndows, does it need to be formatted as:

C:\\Users\\

Or do escapes not apply on Windows? My script is currently giving me something like "Non-ASCII character" at the line import os, so I can't really test this.

tkbx
  • 15,602
  • 32
  • 87
  • 122

3 Answers3

5

Try adding an "r", do as below:

path = r"C:\mypaht\morepaht\myfie.file"
Netwave
  • 40,134
  • 6
  • 50
  • 93
  • works for me I think: f = open("C:\a\a.txt") Traceback (most recent call last): File "", line 1, in IOError: [Errno 22] invalid mode ('r') or filename: 'C:\x07\x07.txt' f = open(r"C:\a\a.txt") – Netwave Oct 18 '12 at 11:41
  • 3
    @DanielSanchez, raw strings can't end in '\' – John La Rooy Oct 18 '12 at 11:43
  • @gnibbler but if I want a subdirectory to that, I can do `newpath = r"%s\something"` (assuming myfile was a directory) – tkbx Oct 19 '12 at 10:29
3

Short answer: Use forward slash instead as suggested by gnibbler.

On using raw strings:

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

In [9]: a=r'\\'

In [10]: b=r'\\\'
  File "<ipython-input-10-9f86439e68a3>", line 1
    b=r'\\\'
             ^
SyntaxError: EOL while scanning string literal


In [11]: a
Out[11]: '\\\\'
root
  • 76,608
  • 25
  • 108
  • 120
3

You should not construct file paths that way. Its not portable and error prone.

Use the join() function from os.path

import os.path
path = os.path.join('C:', 'Users', 'name')
Ber
  • 40,356
  • 16
  • 72
  • 88
  • Does this automatically use backslashes on Windows, and slashes on every other operating system? – tkbx Oct 18 '12 at 13:07