Getting Home Path and Username in Python
Getting home path and username in python, were just an one liners for me so for : os.path.expanduser(”~/”) and pwd.getpwuid(os.getuid())[0] were doing the job for me, but when a friend was stuck with doing the same for multiple platforms he was facing few issues, so played a bit with it and came up with some silly code that worked for him, thought it was wroth sharing the code snippet with you guys, hoping it will get better!
Getting the home path :
import os
home = os.curdir
if ‘HOME’ in os.environ:
home = os.environ['HOME']
elif os.name == ‘posix’:
home = os.path.expanduser("~/")
elif os.name == ‘nt’:
if 'HOMEPATH' in os.environ and 'HOMEDRIVE' in os.environ:
home = os.environ['HOMEDRIVE'] + os.environ['HOMEPATH']
else:
home = os.environ['HOMEPATH']
Code for getting the current user :
import os
for name in (‘LOGNAME’, ‘USER’, ‘LNAME’, ‘USERNAME’):
user = os.environ.get(name)
if user:
return user
# If not user from os.environ.get()
import pwd
return pwd.getpwuid(os.getuid())[0]
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.