-1

I would like to replace the backslash \ in a windows path with forward slash / using python. Unfortunately I'm trying from hours but I cannot solve this issue.. I saw other questions here but still I cannot find a solution Can someone help me?

This is what I'm trying:

path = "\\ftac\admin\rec\pir"
path = path.replace("\", "/")

But I got an error (SyntaxError: EOL while scanning string literal) and is not return the path as I want: //ftac/admin/rec/pir, how can I solve it?

I also tried path = path.replace(os.sep, "/") or path = path.replace("\\", "/") but with both methods the first double backslash becomes single and the \a was deleted..

Joss Fres
  • 15
  • 3

1 Answers1

1

Oh boy, this is a bit more complicated than first appears.

Your problem is that you have stored your windows paths as normal strings, instead of raw strings. The conversion from strings to their raw representation is lossy and ugly.

This is because when you make a string like "\a", the intperter sees a special character "\x07".

This means you have to manually know which of these special characters you expect, then [lossily] hack back if you see their representation (such as in this example):

def str_to_raw(s):
    raw_map = {8:r'\b', 7:r'\a', 12:r'\f', 10:r'\n', 13:r'\r', 9:r'\t', 11:r'\v'}
    return r''.join(i if ord(i) > 32 else raw_map.get(ord(i), i) for i in s)

>>> str_to_raw("\\ftac\admin\rec\pir")
'\\ftac\\admin\\rec\\pir'

Now you can use the pathlib module, this can handle paths in a system agnsotic way. In your case, you know you have Windows like paths as input, so you can use as follows:

import pathlib

def fix_path(path):
    # get proper raw representaiton
    path_fixed = str_to_raw(path)

    # read in as windows path, convert to posix string
    return pathlib.PureWindowsPath(path_fixed).as_posix()

>>> fix_path("\\ftac\admin\rec\pir")
'/ftac/admin/rec/pir'

Matt
  • 1,196
  • 1
  • 9
  • 22
  • WOW! Thanks Matt, not it is more clear, to be honest I tough it was easier :) Thanks a lot really for your help. I tried the same with a different path ("C:\Users\ftac\"), but now I have the (unicode error) 'unicodeescape' codec error, I saw that putting a r in front of the "..." is fixing it, do you know by any chance if there is also another way? Thanks in advance – Joss Fres Nov 25 '22 at 15:06
  • 1
    `"C:\Users\ftac\"` can never be interpretted as a valid string, as you said you will have to define it as a raw string `r"C:\Users\ftac\"`. How are you expecting to populate your original path strings? One way is to simply not write the final \ e.g. `"C:\Users\ftac"` – Matt Nov 25 '22 at 15:08
  • 1
    also your probelm here is `"\U"` is another problem character that cannot be parsed properly, you either have to define the whole string as a raw string at the beginning, or you have to double escape all \ with \\ – Matt Nov 25 '22 at 15:12