1

I am trying to convert Windows file path to Unix using os.path.normpath. I am getting unexpected characters in file path.

import os
path1 = 'C:\Users\abcd\dir1'
path2 = os.path.normpath(path1)
path2

I want to replace "\" by "/". But output is 'C:\\Users\x07bcd\\dir1'. I am wondering how x07` comes in the picture and how to get rid of it.

Alternatively, I tried regex to replace "\" by "/".

Desired output is: 'C:/Users/abcd/dir1'

I tried using answer of Python how to replace backslash with re.sub() but could not get it to work. If I want to use it, can someone suggest how to do it?

path3 = re.sub(path1 +"\\" "//")

But there is error. I am new to python, so could not figure out proper syntax.

sarf34
  • 13
  • 3
  • 3
    Use a raw string `r'C:\Users\abcd\dir1'`. Otherwise, `\a` gets treated as the sequence for the BEL character, `\x07` == Ctrl-G. – PM 2Ring Jun 06 '17 at 14:23
  • Don't use regex for this. When handling paths use functions that are built to do that job, like the `os.path` functions. – PM 2Ring Jun 06 '17 at 14:48

1 Answers1

1

Use raw string or double slash in this case :

path1 = 'C:\\Users\\abcd\dir1'

or

path1 = r'C:\Users\abcd\dir1'
developer_hatch
  • 15,898
  • 3
  • 42
  • 75