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?
By default the <Leader> key is backslash, and <Bslash> is a way to refer to a backslash in a mapping, so by default these commands map \/ and \\ respectively. Press \/ to change every backslash to a forward slash, in the current line. Press \\ to change every forward slash to a backslash, in the current line.
We can use the replace() function to replace the backslashes in a string with another character. To replace all backslashes in a string, we can use the replace() function as shown in the following Python code.
Programming languages, such as Python, treat a backslash (\) as an escape character. For instance, \n represents a line feed, and \t represents a tab. When specifying a path, a forward slash (/) can be used in place of a backslash.
Just use . replace() twice! first operation creates ** for every \ and second operation escapes the first slash, replacing ** with a single \ .
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.
I recently found this and thought worth sharing:
import os path = "C:\\temp\myFolder\example\\" newPath = path.replace(os.sep, '/') print newPath Output:<< C:/temp/myFolder/example/ >>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With