To get the current username in Python, the easiest way is with the os module getlogin() function.
import os
print(os.getlogin())
#Output:
The Programming Expert
Another way you can get the current username is from the dictionary of environment variables of the operating system.
import os
print(os.environ.get("USERNAME"))
#Output:
The Programming Expert
One other way you can get the username is with the os module path.expanduser() function.
import os
print(os.path.expanduser("~"))
#Output:
C:UsersThe Programming Expert
In Python, the os module provides us with many useful functions which allow us to get information about the operating system and environment we are working with.
One piece of information which can be valuable is the current logged in user and the username of that user.
There are a few ways you can get the current username in Python.
The easiest way to get the name of the current user in Python is with the os module getlogin() function.
Below shows a simple example of using getlogin() to get the current username in Python.
import os
print(os.getlogin())
#Output:
The Programming Expert
Another way you can get the current username is from the dictionary of environment variables of the operating system.
You can access the dictionary of environment variables with the environ dictionary.
Then, to get the username, use get() to get the username value.
Below shows you how to use the dictionary of environment variables to get the username in Python.
import os
print(os.environ.get("USERNAME"))
#Output:
The Programming Expert
One other way you can get the username is with the os module path.expanduser() function.
You can use this method if you want to get the root of the user path.
Below shows you how to use path.expanduser() to get the username in Python.
import os
print(os.path.expanduser("~"))
#Output:
C:UsersThe Programming Expert
Hopefully this article has been useful for you to get the current username in Python.