I have a string as such:

str = 'C:\Process new\RF\test.dat'
I need to replace all the backslashes with '/':
res = 'C:/Process new/RF/test.dat'

It is NOT a straight forward search and replace as I need to replace escape sequence (\).

Any ideas?

that one only does this:
C:/Process new\RF\test.dat

It does not replace all the backslashes. Its got something to do with how Python uses repr().

You are right my mistake.

It is not because of repr.

The string:
'C:\Process new\RF\test.dat'

Has only one backslash. The other karakters are escape sequenses. Try to print it.

If you want the string literally, use r'C:\Process new\RF\test.dat' and replace the backslash on that.

Windows path gotchas

Just for the record.
Do not use window path strings as path strings.

The string:
'C:\Process new\RF\test.dat'
Does not mean what you expect. There are escape sequences in it.
Does not point to the file you expected. Using open on this will not find the file.

The ways to do this:
os.path.join("c:", "Process new","RF","test.dat")
or
os.path.normpath('c:/Process new/RF/test.dat')
or in case of need
r'C:\Process new\RF\test.dat ' (note the space in the end)

http://mail.python.org/pipermail/tutor/2004-May/029510.html

Edited 6 Years Ago by slate: n/a

Just for the record.
Do not use window path strings as path strings.
...
The ways to do this:
os.path.join("c:", "Process new","RF","test.dat")

Slate,

Just a minor correction in your example. For some reason on Windows the os.path.join function does not play nice with drive letters. When using a drive letter you still need to have backslashes, ie:

>>> os.path.join("c:", "Process new","RF","test.dat")
'c:Process new\\RF\\test.dat'
>>> os.path.join("c:\\", "Process new","RF","test.dat")
'c:\\Process new\\RF\\test.dat'

Thanks.

I googled the net, if someone had made a usable guide on this.
I have only found blogs about, how it sucks.

Personally I try to avoid absolute path names, and use os.path package extensivelly.

This article has been dead for over six months. Start a new discussion instead.