25

I am facing a very basic problem using directory path in python script. When I do copy path from the windows explorer, it uses backward slash as path seperator which is causing problem.

>>> x
'D:\testfolder'
>>> print x
D:      estfolder
>>> print os.path.normpath(x)
D:      estfolder
>>> print os.path.abspath(x)
D:\     estfolder
>>> print x.replace('\\','/')
D:      estfolder

Can some one please help me to fix this.

sarbjit
  • 3,786
  • 9
  • 38
  • 60
  • Forward slashes are understood on all OSes - but `normpath` on windows does use `\\`. I personally find it easiest to use the `path` methods to combine/manage paths and then finally do a replace from `\\` to `/` to be consistent across systems. Not sure if that answers your Q? – Basic Sep 28 '13 at 08:52
  • 5
    you could add a r before this string, for example, x = r'D:\testfolder', and x would be "D:\testfolder". adding a 'r' before a string shows this string is a raw string. – Mark Sep 28 '13 at 09:05

1 Answers1

24

Python interprets a \t in a string as a tab character; hence, "D:\testfolder" will print out with a tab between the : and the e, as you noticed. If you want an actual backslash, you need to escape the backslash by entering it as \\:

>>> x = "D:\\testfolder"
>>> print x
D:\testfolder

However, for cross-platform compatibility, you should probably use os.path.join. I think that Python on Windows will automatically handle forward slashes (/) properly, too.

mipadi
  • 398,885
  • 90
  • 523
  • 479
  • 11
    Just using forward slashes will work under windows - `os.path.join()` is obviously the strongest solution. – Gareth Latty Sep 28 '13 at 09:15
  • 29
    Alternatively, you can use a [raw string literal](http://docs.python.org/2/reference/lexical_analysis.html#string-literals) by prefixing an `r` so that escape sequences are not interpreted, e.g. `r"D:\testfolder"`. – Adam Rosenfield Sep 30 '13 at 18:36
  • 4
    @AdamRosenfield Raw strings are not suited for windows path. https://pythonconquerstheuniverse.wordpress.com/2008/06/04/gotcha-%E2%80%94-backslashes-in-windows-filenames/ – Dmitrii Dovgopolyi Jun 18 '15 at 13:48
  • 1
    Raw strings are not *always* suited for windows paths. From the link, raw strings will work as long as you don't end them in \. Alternatively os.path.normpath() and os.path.join() in combination, will work if used consistently. – knickum Jun 30 '15 at 22:24