Hướng dẫn python escape forward slash

I hope someone can help as I am stuck, I can't find the answer to this problem anywhere on google.

Nội dung chính

  • Not the answer you're looking for? Browse other questions tagged python replace or ask your own question.
  • How do I enable backslash in Python?
  • How do I change a backslash in Python?
  • Does Python use backslash or forward slash?
  • How do you change backward slash to forward slash?

I need to replace my forward slash path with a backslash path in order for it to work with windows command prompt. Forward slash paths work for local folders, i.e. C:/Users/Lorcan - but not network folders, i.e. //Networkfolder/Storage

I learned that you can't use the backslash in python as it is a special character, so you must use two backslashes. However, this causes my path to have too many backslashes, and command prompt doesn't work.

>>> s = '//Networkfolder/Storage/Myfolder/Myfile'
>>> s2 = s.replace('/','\\')
>>> s2
'\\\\Networkfolder\\Storage\\Myfolder\\Myfile'

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

Nội dung chính

  • Not the answer you're looking for? Browse other questions tagged python replace or ask your own question.
  • How do I enable backslash in Python?
  • How do I change a backslash in Python?
  • Does Python use backslash or forward slash?
  • How do you change backward slash to forward slash?
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

115k25 gold badges160 silver badges282 bronze badges

asked Aug 5, 2014 at 19:39

3

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

115k25 gold badges160 silver badges282 bronze badges

answered May 7, 2018 at 19:27

NumabyteNumabyte

7405 silver badges6 bronze badges

1

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.

answered Aug 5, 2014 at 19:47

Jason SJason S

13.1k2 gold badges35 silver badges42 bronze badges

3

Try

path = '/'.join(path.split('\\'))

answered Aug 5, 2014 at 19:41

TheoretiCALTheoretiCAL

17.9k8 gold badges38 silver badges63 bronze badges

1

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.

answered Jun 28, 2018 at 7:39

scapascapa

1191 silver badge6 bronze badges

1

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"

answered May 14, 2021 at 14:55

StefanStefan

1112 silver badges8 bronze badges

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

answered Mar 21, 2018 at 10:53

Mohammad ElNesrMohammad ElNesr

2,3373 gold badges27 silver badges42 bronze badges

1

How about :

import ntpath
import posixpath
.
.
.
dir = posixpath.join(*ntpath.split(s))
.
.

answered Sep 28, 2017 at 6:29

1

This can work also:

def slash_changer(directory):

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

print(slash_changer(os.getcwd()))

answered Nov 19, 2021 at 22:04

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

answered Mar 26 at 11:02

Not the answer you're looking for? Browse other questions tagged python replace or ask your own question.

How do I enable backslash in Python?

In short, to match a literal backslash, one has to write '\\\\' as the RE string, because the regular expression must be "\\", and each backslash must be expressed as "\\" inside a regular Python string literal.

How do I change a backslash in Python?

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.

Does Python use backslash or forward slash?

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. Two backslashes can be used instead of one to avoid a syntax error.

How do you change backward slash to forward slash?

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.