How to Find the Real User Home Directory Using Python

What is a cross-platform way to get the home directory?

You want to use os.path.expanduser.

This will ensure it works on all platforms:

from os.path import expanduser
home = expanduser("~")

If you're on Python 3.5+ you can use pathlib.Path.home():

from pathlib import Path
home = str(Path.home())

How to find the real user home directory using python?

I think os.path.expanduser(path) could be helpful.

On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user‘s home directory.

On Unix, an initial ~ is replaced by the environment variable HOME if it is set; otherwise the current user’s home directory is looked up in the password directory through the built-in module pwd. An initial ~user is looked up directly in the password directory.

On Windows, HOME and USERPROFILE will be used if set, otherwise a combination of HOMEPATH and HOMEDRIVE will be used. An initial ~user is handled by stripping the last directory component from the created user path derived above.

If the expansion fails or if the path does not begin with a tilde, the path is returned unchanged.

So you could just do:

os.path.expanduser('~user')

Find home directory in 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()

Find /home/user in python as root user

import os
username = os.getenv("USER")
if(username != 'root'):
print(os.path.expanduser('~'+username))

python - Finding the user's Downloads folder

Correctly locating Windows folders is somewhat of a chore in Python. According to answers covering Microsoft development technologies, such as this one, they should be obtained using the Vista Known Folder API. This API is not wrapped by the Python standard library (though there is an issue from 2008 requesting it), but one can use the ctypes module to access it anyway.

Adapting the above answer to use the folder id for downloads shown here and combining it with your existing Unix code should result in code that looks like this:

import os

if os.name == 'nt':
import ctypes
from ctypes import windll, wintypes
from uuid import UUID

# ctypes GUID copied from MSDN sample code
class GUID(ctypes.Structure):
_fields_ = [
("Data1", wintypes.DWORD),
("Data2", wintypes.WORD),
("Data3", wintypes.WORD),
("Data4", wintypes.BYTE * 8)
]

def __init__(self, uuidstr):
uuid = UUID(uuidstr)
ctypes.Structure.__init__(self)
self.Data1, self.Data2, self.Data3, \
self.Data4[0], self.Data4[1], rest = uuid.fields
for i in range(2, 8):
self.Data4[i] = rest>>(8-i-1)*8 & 0xff

SHGetKnownFolderPath = windll.shell32.SHGetKnownFolderPath
SHGetKnownFolderPath.argtypes = [
ctypes.POINTER(GUID), wintypes.DWORD,
wintypes.HANDLE, ctypes.POINTER(ctypes.c_wchar_p)
]

def _get_known_folder_path(uuidstr):
pathptr = ctypes.c_wchar_p()
guid = GUID(uuidstr)
if SHGetKnownFolderPath(ctypes.byref(guid), 0, 0, ctypes.byref(pathptr)):
raise ctypes.WinError()
return pathptr.value

FOLDERID_Download = '{374DE290-123F-4565-9164-39C4925E467B}'

def get_download_folder():
return _get_known_folder_path(FOLDERID_Download)
else:
def get_download_folder():
home = os.path.expanduser("~")
return os.path.join(home, "Downloads")

A more complete module for retrieving known folders from Python is available on github.

How can I find script's directory?

You need to call os.path.realpath on __file__, so that when __file__ is a filename without the path you still get the dir path:

import os
print(os.path.dirname(os.path.realpath(__file__)))

How to account for changes in name of user

Use ~ to represent the user's home directory, and then you can use os.path.expanduser to expand it to the full path for the current user.

If you are logged in as Jon and your home directory is /Users/Jon, then

import os

print(os.path.expanduser("~/Desktop/namelisttext.txt"))

Will print:

/Users/Jon/Desktop/namelisttext.txt

The great thing about os.path.expanduser is that it's not specific to one OS. It will do the right thing on any OS that Python supports, including Windows, where ~ is not normally used otherwise.

Can't get the correct paths of files inside a hidden directory

This actually has nothing to do with hidden directories, but rather with a confusion with how os.listdir works. If you look at the results of os.listdir(dir), you'll see that it returns the base file name of the files in the directory. A file with the path /home/user/myproject/.hidden_dir/last_dir/project.py will be represented as "project.py" in the result. The Path() object doesn't check if the path you pass in actually exists, and if it's not an absolute path, it will assume it's under the current working directory. In this case, it seems like the working directory was /home/user/myproject/, giving you the weird results you saw.

The right way to do something like this would be

dir_path = Path("/home/user/myproject/.hidden_dir/last_dir")
for file_path in filter(lambda p: p.is_file(), dir_path.iterdir()):
print(file_path.absolute())


Related Topics



Leave a reply



Submit