60

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

Community
  • 1
  • 1
WeaselFox
  • 7,220
  • 8
  • 44
  • 75

2 Answers2

146

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()

Stan James
  • 2,535
  • 1
  • 28
  • 35
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • `os.environ['HOME']` seems more intuitive for me, because I often use `$HOME` in Linux. But could you point out some use cases where using `expanduser` might be more preferable? – flow2k Sep 25 '19 at 21:12
25

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

Michael Wild
  • 24,977
  • 3
  • 43
  • 43