[파이썬] os 환경 변수 확장: `os.path.expandvars()`

In Python, the os.path.expandvars() function is a useful tool for expanding the values of environment variables within a string. This can be particularly helpful when you need to work with file paths that contain environment variables, as it allows you to easily replace them with their corresponding values.

How os.path.expandvars() works

The os.path.expandvars() function takes a string as input and returns a new string with any embedded environment variables expanded. It searches for substrings in the form $name or ${name} and replaces them with the corresponding value from the environment.

Here’s a basic example to illustrate how it works:

import os

path = "$HOME/Documents"

expanded_path = os.path.expandvars(path)
print(expanded_path)

In this example, the $HOME environment variable is expanded to its actual value before being printed. If the value of $HOME is /Users/username, the output will be /Users/username/Documents.

Using os.path.expandvars() in file paths

One of the most common use cases for os.path.expandvars() is when working with file paths that contain environment variables. Let’s say you have a file path template that includes the $USERNAME environment variable:

import os

file_template = "/home/$USERNAME/data.txt"
username = "john.doe"

file_path = file_template.replace("$USERNAME", username)
expanded_file_path = os.path.expandvars(file_path)

print(expanded_file_path)

In this example, we first replace the $USERNAME placeholder with the actual username. Then, we pass the resulting file path to os.path.expandvars() to ensure that any other environment variables are expanded. The output will be /home/john.doe/data.txt.

Conclusion

Using os.path.expandvars() in Python allows you to easily work with environment variable-expanded strings, particularly when dealing with file paths. It saves you from manually replacing the variables with their values and ensures that your code works correctly across different environments.

So, next time you encounter a string containing environment variables, remember to leverage os.path.expandvars() to simplify your code and make it more robust.