How to make Python get the username in windows and then implement it in a script

Question:

I know that using
getpass.getuser() command, I can get the username, but how can I implement it in the following script automatically? So i want python to find the username and then implement it in the following script itself.

Script: os.path.join('..','Documents and Settings','USERNAME','Desktop'))

(Python Version 2.7 being used)

Asked By: KingMak

||

Answers:

os.getlogin() return the user that is executing the, so it can be:

path = os.path.join('..','Documents and Settings',os.getlogin(),'Desktop')

or, using getpass.getuser()

path = os.path.join('..','Documents and Settings',getpass.getuser(),'Desktop')

If I understand what you asked.

Answered By: Gianluca

Install win32com, then:

from win32com.shell import shell, shellcon
print shell.SHGetFolderPath(0, shellcon.CSIDL_DESKTOP, None, 0)
Answered By: Burhan Khalid
>>> os.path.join(os.path.expandvars("%userprofile%"),"Documents and Settings")
'C:\Users\USERNAME\Documents and Settings'

should suffice … I think thats what you actually meant anyway..

Answered By: Joran Beasley

os.getlogin() did not exist for me. I had success with os.getenv('username') however.

Answered By: CodeJockey

to get the current user directory you can also use this:

from os.path import expanduser
home = expanduser("~buildconf")
Answered By: cinatic

This works for Python 3.* as well:

os.path.join(os.environ['HOME'] + "/Documents and Settings")
Answered By: Natalia

If you want the desktop directory, Windows 7 has an environment variable: DESKTOP:

>>> import os
>>> print(os.environ['desktop'])
C:UsersKingMakDesktop
Answered By: Peter Wood

you can try the following as well:


import os
print (os.environ['USERPROFILE'])

The advantage of this is that you directly get an output like:

C:\Users\user_name
Answered By: outcast_dreamer

for get current username:
add import os in code
and then use by :

print(os.getlogin())

OR

print(os.getenv('username'))

and if you get complete path from c drive use this :

print(os.environ['USERPROFILE']) #C:Usersusername
Answered By: mamal

import os followed by os.getlogin() works on macOS and Windows with python 3.7

After this you can do something like:

path = ''.join(('C:/Users/', os.getlogin(), '/Desktop/'))
Answered By: Saurabh
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.