Find "home directory" in Python?

PythonLinux

Python Problem Overview


> Possible Duplicate:
> How to find the real user home directory using python?
> How to get the home directory in Python?

I want to access /home/weasel to read some files from there but I don't want to write the full path of course - so other users can use the script.. how do you know your username or your home dir with python on Linux?

Thanks

Python Solutions


Solution 1 - Python

To get the homedir in python, you can use os.path.expanduser('~').

This also works if it's part of a longer path, such as os.path.expanduser('~/some/directory/file.txt'). If there is no ~ in the path, the function will return the path unchanged.

So depending on what you want to do it's better than reading os.environ['HOME']

The username is available through getpass.getuser()

Solution 2 - Python

The portable way of getting the home directory in Python is using os.path.expanduser('~').

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWeaselFoxView Question on Stackoverflow
Solution 1 - PythonThiefMasterView Answer on Stackoverflow
Solution 2 - PythonMichael WildView Answer on Stackoverflow