18

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?

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
  • 4
    `r'\dir\anotherdir\foodir\more'.replace('\\', '/')` works just fine. – Glenn Maynard Nov 07 '10 at 20:34
  • 2
    Your error occurs because you typed `\dir\anotherdir\foodir\more` as a string yourself, and `\f` is special. If you want Python not to interpret special characters (characters prefixed by backslashes) you should use “raw” strings, e.g: `r'\dir\anotherdir\foodir\more'` – tzot Nov 08 '10 at 20:05
  • 1
    `os.path.abspath` will convert them to unified format. – Lei Yang Feb 22 '19 at 08:20

3 Answers3

27

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'
Stefano M
  • 4,267
  • 2
  • 27
  • 45
13

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.

Tomasz Zieliński
  • 16,136
  • 7
  • 59
  • 83
11

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.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • 2
    I cannot see any functions in os.path related to replacing backslashes with forwardslashes. Could you please elaborate? – Alex Spurling Aug 14 '17 at 11:55
  • The functions in `os.path` are designed so you don't have to care what kind of slashes your paths contain. E.g. if you use `os.path.join` to join paths, it will use the appropriate separator for your platform. – Björn Pollex Aug 14 '17 at 15:37
  • 5
    Thanks, so just to be clear there are no functions in os.path that actually replace slashes, just functions that allow you to avoid dealing with path separators. – Alex Spurling Aug 16 '17 at 11:02
  • 1
    This question was about how to replace backslashes not how to join files. – catubc Aug 10 '22 at 09:11