Hi,
I’ve been struggling with windows path for a while because of Python regex.
When I need my user to input a path variable in a tool, if they give a classical windows path Python will convert ‘’ because of regex. os.path.normpath don’t seem to work.
path = 'L:\sandbox\20_lookdev\10_asset\character\assetName\model\scenes\publish'
os.path.normpath(path)
>>>> 'L:\\sandbox\x10_lookdev\x08_asset\\character\x07ssetName\\model\\scenes\\publish' #
I modified the function ‘rawString’ found on the internet which is supposed to clean those nasty ‘’, but it works randomly:
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
But same problem:
slashPath(path)
>>>> 'L:/sandbox\x10_lookdev/b_asset/character/7ssetName/model/scenes/publish'
Does anyone know how we are supposed to work with those path? I’m searching for a solution that works 100% of the time.
Thanks