TartanLlama
TartanLlama

Reputation: 65770

Replace Backslashes with Forward Slashes in Python

I'm writing a cross platform file explorer in python. I am trying to convert any backslashes in a path into forward slashes in order to deal with all paths in one format.

I've tried not only using string.replace(str, '\\', '/'), but also creating a method manually to search through the string and replace the instances, and both do not work properly, as a path name such as:

\dir\anotherdir\foodir\more

changes to:

/dir/anotherdir\x0oodir/more

I am assuming that this has something to do with how Python represents escape characters or something of the sort. How do I prevent this happening?

Upvotes: 20

Views: 59841

Answers (3)

Stefano M
Stefano M

Reputation: 4818

Elaborating this answer, with pathlib you can use the as_posix method:

>>> import pathlib
>>> p = pathlib.PureWindowsPath(r'\dir\anotherdir\foodir\more')
>>> print(p)    
\dir\anotherdir\foodir\more
>>> print(p.as_posix())
/dir/anotherdir/foodir/more
>>> str(p)
'\\dir\\anotherdir\\foodir\\more'
>>> str(p.as_posix())
'/dir/anotherdir/foodir/more'

Upvotes: 33

Björn Pollex
Björn Pollex

Reputation: 76886

You should use os.path for this kind of stuff. In Python 3, you can also use pathlib to represent paths in a portable manner, so you don't have to worry about things like slashes anymore.

Upvotes: 12

Tomasz Zieliński
Tomasz Zieliński

Reputation: 16377

Doesn't this work:

    >>> s = 'a\\b'
    >>> s
    'a\\b'
    >>> print s
    a\b
    >>> s.replace('\\','/')
    'a/b'

?

EDIT:

Of course this is a string-based solution, and using os.path is wiser if you're dealing with filesystem paths.

Upvotes: 14

Related Questions