Python Convert Back Slashes to forward slashes

前端 未结 6 1882
滥情空心
滥情空心 2020-12-15 16:11

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(\'\\\\         


        
相关标签:
6条回答
  • 2020-12-15 16:30

    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/  >>
    
    0 讨论(0)
  • 2020-12-15 16:31

    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.

    0 讨论(0)
  • 2020-12-15 16:40

    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

    0 讨论(0)
  • 2020-12-15 16:46

    How about :

    import ntpath
    import posixpath
    .
    .
    .
    dir = posixpath.join(*ntpath.split(s))
    .
    .
    
    0 讨论(0)
  • 2020-12-15 16:48

    Try

    path = '/'.join(path.split('\\'))
    
    0 讨论(0)
  • 2020-12-15 16:54

    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.

    0 讨论(0)
提交回复
热议问题