30

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.

2
  • 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? Commented Sep 28, 2013 at 8:52
  • 6
    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. Commented Sep 28, 2013 at 9:05

1 Answer 1

28

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Just using forward slashes will work under windows - os.path.join() is obviously the strongest solution.
Alternatively, you can use a raw string literal by prefixing an r so that escape sequences are not interpreted, e.g. r"D:\testfolder".
@AdamRosenfield Raw strings are not suited for windows path. pythonconquerstheuniverse.wordpress.com/2008/06/04/…
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.