python - Converting a windows path to a path using environment variables -
is there python library takes windows path , replaces expanded environment variables environment variables?
for example:
c:\users\username\documents\text.txt -> %userprofile%\documents\text.txt c:\windows\system32\cmd.exe -> %windir%\system32\cmd.exe c:\program files\program\program.exe -> %programfiles%\program\program.exe
the best way explain functionality opposite of
os.path.expandvars('some path environment variables')
support different languages requirement.
c:\archivos de programa\progra\program.exe -> %programfiles%\program\program.exe
this non-trivial problem since more environment variables may match parts of string (ex: processor_level
single digit, should avoid it). ensure best efficiency, would:
- sort existing environment variable l
like this:
import os my_string = os.path.normpath(r"d:\users\jotd\appdata\roaming\adobe\flash player") k,v in sorted(os.environ.items(),key=lambda x:len(x[1]),reverse=true): my_new_string = my_string.replace(v+os.sep,"%{}%{}".format(k,os.sep)) if my_string != my_new_string: break my_string = my_new_string print(my_new_string)
Comments
Post a Comment