KingMak
KingMak

Reputation: 1478

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

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)

Upvotes: 49

Views: 151058

Answers (10)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24164

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

>>> import os
>>> print(os.environ['desktop'])
C:\Users\KingMak\Desktop

Upvotes: 5

Saurabh
Saurabh

Reputation: 6960

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/'))

Upvotes: 4

mamal
mamal

Reputation: 2006

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:\Users\username

Upvotes: 11

outcast_dreamer
outcast_dreamer

Reputation: 163

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

Upvotes: 3

Natalia
Natalia

Reputation: 385

This works for Python 3.* as well:

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

Upvotes: 1

user1092803
user1092803

Reputation: 3297

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.

Upvotes: 90

cinatic
cinatic

Reputation: 969

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

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

Upvotes: 2

CodeJockey
CodeJockey

Reputation: 1981

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

Upvotes: 51

Joran Beasley
Joran Beasley

Reputation: 114088

>>> 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..

Upvotes: 7

Burhan Khalid
Burhan Khalid

Reputation: 174708

Install win32com, then:

from win32com.shell import shell, shellcon
print shell.SHGetFolderPath(0, shellcon.CSIDL_DESKTOP, None, 0)

Upvotes: 5

Related Questions