I’ve been using this for the past months:
import os
import re
def slashPath(path):
"""
param: str file path
return: str file path with "\\" replaced by '/'
"""
path = rawString(path)
raw_path = r"{}".format(path)
separator = os.path.normpath("/")
changeSlash = lambda x: '/'.join(x.split(separator))
if raw_path.startswith('\\'):
return '/' + changeSlash(raw_path)
else:
return changeSlash(raw_path)
def rawString(strVar):
"""Returns a raw string representation of strVar.
Will replace '\\' with '/'
:param: str String to change to raw
"""
if type(strVar) is str:
strVarRaw = r'%s' % strVar
new_string=''
escape_dict={'\a':r'\a', '\b':r'\b', '\c':r'\c', '\f':r'\f', '\n':r'\n',
'\r':r'\r', '\t':r'\t', '\v':r'\v', '\'':r'\'', '\"':r'\"',
'\0':r'\0', '\1':r'\1', '\2':r'\2', '\3':r'\3', '\4':r'\4',
'\5':r'\5', '\6':r'\6', '\7':r'\7', '\8':r'\8', '\9':r'\9'}
for char in strVarRaw:
try: new_string+=escape_dict[char]
except KeyError: new_string+=char
return new_string
else:
return strVar
slashPath(path) will always give a path with ‘/’ as sep.