2

Is there a Python library that takes a windows path and replaces expanded environment variables with 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 to explain would be to get functionality that does the opposite of

os.path.expandvars('some path with environment variables')

Support for different languages would also be a requirement.

C:\Archivos de programa\Progra\Program.exe -> %PROGRAMFILES%\Program\Program.exe
3
  • 2
    I don't think that is possible, or at least it is ambiguous. There is nothing to say that there is a one-to-one mapping of directories to environment variables. In other words I could have both %FOO% and %BAR% that both expand to C:\Windows, in that case which should I use? Commented Jul 25, 2017 at 12:43
  • There is a winshell module, specifically its Special Folders part that grabs some of the special folders. For the rest you'll have to use Win32 API. Then it's just a matter of checking if your path intersects with the special folder and replacing it with its canonical environment variable name - you can use the os.path facilities for that. Commented Jul 25, 2017 at 12:46
  • @CoryKramer it only needs to map to known default windows environment variables, not any new ones. Commented Jul 25, 2017 at 12:52

1 Answer 1

1

This is a non-trivial problem since more than environment variables may match parts of your string (ex: PROCESSOR_LEVEL is usually a single digit, so you should avoid it). To ensure the best efficiency, I would:

  • sort the existing environment variable l

like this:

import os

my_string = os.path.normpath(r"D:\Users\JOTD\AppData\Roaming\Adobe\Flash Player")


for 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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.