-1

Currently I'm trying to save the username as a variable. Since this script will be going to other people, I'm trying to find the username, and save it as a variable, then use that variable in filepaths. Ex:

import getpass
username = getpass.getuser()
os.chdir('/home/{username}/')
<other code>

I'm still very new to Python, so if you can help me, and explain what it does, that would be greatly appreciated. Using Linux Ubuntu, so Windows solutions wouldn't be very helpful.

EDIT:

As it python 2.7 the above f-string won't work. Use '/home/{}/'.format(username) – Sergey Pugach

Thank you Sergey Pugach, that solved my problem perfectly. Thank the rest of y'all for solving my question within the pass 2 hours. Have a nice day!

Lunar
  • 480
  • 4
  • 11
  • Use Python 3.x+ and `f'/home/{username}/'` should work. – Austin Jan 31 '19 at 15:49
  • 1
    As it python 2.7 the above `f-string` won't work. Use `'/home/{}/'.format(username)` – Sergey Pugach Jan 31 '19 at 15:50
  • 1
    Small tip, not all homes are of this format, your can use `os.environ['HOME']` should be more portable. – Taek Jan 31 '19 at 15:51
  • 2
    If you're a beginner, you should learn the newest version of Python, Python _3_.7, as the whole 2.x branch will be discontinued in 2020. – ForceBru Jan 31 '19 at 15:51
  • for working with paths you should default to `os.path.join('/home', username)`. May not always be necessary but it will save you more headaches then it'll cause you. – gbtimmon Jan 31 '19 at 15:53
  • Possible duplicate of [How to find the real user home directory using python?](https://stackoverflow.com/questions/2668909/how-to-find-the-real-user-home-directory-using-python) – handras Jan 31 '19 at 15:55

3 Answers3

1

As written on https://docs.python.org/2/library/getpass.html

getpass.getuser() Return the “login name” of the user.

This function checks the environment variables LOGNAME, USER, LNAME and USERNAME, in order, and returns the value of the first one which is set to a non-empty string. If none are set, the login name from the password database is returned on systems which support the pwd module, otherwise, an exception is raised.

tbalaz
  • 159
  • 3
1

You should probably use the expanduser function to get a suiting directory. This makes sure it works on macos, linux and windows.

https://docs.python.org/2/library/os.path.html#os.path.expanduser

Bastian
  • 10,403
  • 1
  • 31
  • 40
0

As it python 2.7 the above f-string won't work. Use '/home/{}/'.format(username) – Sergey Pugach

Thank you Sergey Pugach, that solved my problem perfectly. Thank the rest of y'all for solving my question within the pass 2 hours. Have a nice day!

Lunar
  • 480
  • 4
  • 11