Get Home directory path in Python (win, lin, other?)

/ Published in: Python
Save to your folder(s)

The current user's home directory is probably the easiest way to get a writeable directory, and expanduser does the sensible thing on various OSes.

In case of windows, you can choose to be smarter about *which* directory you pick.

Copy this code and paste it in your HTML
  1. homedir = os.path.expanduser('~')
  3. # on at least windows and linux.
  4. # In windows it points to the user's folder
  5. # (the one directly under Documents and Settings, not My Documents)
  8. # In windows, you can choose to care about local versus roaming profiles.
  9. # You can fetch the current user's through PyWin32.
  10. #
  11. # For example, to ask for the roaming 'Application Data' directory:
  12. # (CSIDL_APPDATA asks for the roaming, CSIDL_LOCAL_APPDATA for the local one)
  13. # (See microsoft references for further CSIDL constants)
  14. try:
  15. from import shellcon, shell
  16. homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0)
  18. except ImportError: # quick semi-nasty fallback for non-windows/win32com case
  19. homedir = os.path.expanduser("~")

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.