56

I am working in python and I need to convert this:

C:\folderA\folderB to C:/folderA/folderB

I have three approaches:

dir = s.replace('\\','/')

dir = os.path.normpath(s) 

dir = os.path.normcase(s)

In each scenario the output has been

C:folderAfolderB

I'm not sure what I am doing wrong, any suggestions?

martineau
  • 119,623
  • 25
  • 170
  • 301
John87
  • 603
  • 1
  • 5
  • 9
  • 3
    Why do you need to convert it? You could use `r'C:\folderA\folderB'` – Andy Aug 05 '14 at 19:40
  • Well `s.replace('//', '\')` shouldn't even run. The `'\'` is invalid, you need to escape backslashes. The correct way would be `s.replace('/', '\\')`. Right now when it's running it will just give you `\f` which is a linefeed character. – Chrispresso Aug 05 '14 at 19:47
  • I think I posted wrong i believe my original string was dir = s.replace('//','\'). I will verify and update the post if thats the case. – John87 Aug 05 '14 at 21:09

10 Answers10

77

I recently found this and thought worth sharing:

import os

path = "C:\\temp\myFolder\example\\"
newPath = path.replace(os.sep, '/')
print(newPath)  # -> C:/temp/myFolder/example/
martineau
  • 119,623
  • 25
  • 170
  • 301
Numabyte
  • 870
  • 1
  • 6
  • 6
35

Your specific problem is the order and escaping of your replace arguments, should be

s.replace('\\', '/')

Then there's:

posixpath.join(*s.split('\\'))

Which on a *nix platform is equivalent to:

os.path.join(*s.split('\\'))

But don't rely on that on Windows because it will prefer the platform-specific separator. Also:

Note that on Windows, since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

Jason S
  • 13,538
  • 2
  • 37
  • 42
  • I just printed the results from my input and noticed the backslashes didn't exist which explains my output. This is was a great explanation though! Thanks! – John87 Aug 05 '14 at 21:51
  • 1
    Good explanation. However it solves partially the problem, because '\t','\n','\b','\s',.. special characters in general are identified, and therefore are not transformed into '/t','/n'... For example 'C:\program\newdirectory' is transformed into 'C:/program\newdirectory – José Crespo Barrios Jun 12 '19 at 11:54
  • Won't this be a problem on *nix platforms, because \ is allowed in filenames there? So a path `foo/bar\baz` will become `foo/bar/baz`, which is probably not what we want. I think using `os.sep` like in @Numabyte's answer is a better cross-platform solution – aravk33 Jul 24 '21 at 10:06
11

Try

path = '/'.join(path.split('\\'))
TheoretiCAL
  • 19,461
  • 8
  • 43
  • 65
7

Sorry for being late to the party, but I wonder no one has suggested the pathlib-library.

pathlib is a module for "Object-oriented filesystem paths"

To convert from windows-style (backslash)-paths to forward-slashes (as typically for Posix-Paths) you can do so in a very verbose (AND platform-independant) fashion with pathlib:

import pathlib

pathlib.PureWindowsPath(r"C:\folderA\folderB").as_posix()
>>> 'C:/folderA/folderB'

Be aware that the example uses the string-literal "r" (to avoid having "\" as escape-char) In other cases the path should be quoted properly (with double backslashes) "C:\\folderA\\folderB"

Stefan
  • 170
  • 3
  • 9
  • Thanks; I've found this to be the best answer (not sure why it's not upvoted more) – Neil Sep 21 '22 at 00:21
  • 2
    Thanks, Neil, of course I agree :-) Especially not having to explicitly deal with "\" and string-replaces accounts for a stable and robust solution. – Stefan Sep 22 '22 at 11:11
  • Yes this is the best answer as `replace('\\', '/')` will not work when using unmodified paths coming from windows! – ForeverLearning Oct 27 '22 at 16:00
6

Path names are formatted differently in Windows. the solution is simple, suppose you have a path string like this:

data_file = "/Users/username/Downloads/PMLSdata/series.csv"

simply you have to change it to this: (adding r front of the path)

data_file = r"/Users/username/Downloads/PMLSdata/series.csv"

The modifier r before the string tells Python that this is a raw string. In raw strings, the backslash is interpreted literally, not as an escape character.

scapa
  • 119
  • 1
  • 6
  • I have `path = 'some\thing'` and then in another function I access the variable path. I wish I could do `rpath`, but it doesn't work anymore. Is there a solution for this case? – NeStack Jun 14 '19 at 10:53
2

To define the path's variable you have to add r initially, then add the replace statement .replace('\\', '/') at the end.

for example:

In>>  path2 = r'C:\Users\User\Documents\Project\Em2Lph\'.replace('\\', '/')
In>>  path2 
Out>> 'C:/Users/User/Documents/Project/Em2Lph/'

This solution requires no additional libraries

Mohammad ElNesr
  • 2,477
  • 4
  • 27
  • 44
  • 1
    I have `path = 'some\thing'` and then in another function I access the variable `path`? I wish I could do `rpath`, but it doesn't work anymore. Is there a solution for this case? – NeStack Jun 13 '19 at 17:05
0

How about :

import ntpath
import posixpath
.
.
.
dir = posixpath.join(*ntpath.split(s))
.
.
  • 1
    Avoid code-only answers please. Provide an explanation to your answer and comment the behavior the OP has. – VP. Sep 28 '17 at 07:48
0

This can work also:

def slash_changer(directory):

if "\\" in directory:
    return directory.replace(os.sep, '/')
else:
    return directory

print(slash_changer(os.getcwd()))

0

One of the problem I came across is occur when you try to change the backslash followed by and immediate integer like

img = "C:\folderA\folderB\61853639372.png"

This will cause changing the file name, to solve this use this code

import os

img = r"C:\folderA\folderB\61853639372.png"
img = os.path.normpath(img)
print(img)

by add an r prefix to the string used to indicate that it should be treated as a "raw string". Raw strings treat backslashes as literal backslashes and do not interpret escape characters.

-1

this is the perfect solution put the letter 'r' before the string that you want to convert to avoid all special characters likes '\t' and '\f'... like the example below:

str= r"\test\hhd"

print("windows path:",str.replace("\\","\\\\"))
print("Linux path:",str.replace("\\","/"))

result:

windows path: \\test\\hhd
Linux path: /test/hhd
Chafik Boulealam
  • 516
  • 5
  • 10