3

I'm attempting to read and write files from a User Directory, (C:\Users\USERNAME\Test Source) But I've been unsuccessful in finding any resources on how I can auto detect the name of the user, USERNAME in the above example, or anyway that I can have it read and write to the directory without knowledge off what a users name is. Could anyone point me towards the right direction or methods for this, if it's even a logical request? I'm not sure how much difference, if any, it makes but this program is being written in Python 2.7.

Andrew Davis
  • 67
  • 1
  • 1
  • 7

4 Answers4

5

The simplest way is this:

import os
print os.path.expanduser('~')

Append your folder to the path like so:

userdir = os.path.expanduser('~')
print os.path.join(userdir, 'Test Source')

Besides requiring the least lines of code, this method has the advantage of working under every OS (Linux, Windows XP / 7 / 8 / etc).

Torben Klein
  • 2,943
  • 1
  • 19
  • 24
0

You can use in windows command line

 echo %username%

or

  whoami

for getting the username of the user who is currently logged in . Store it in a variable and then append it to the path name.

You can also use

‘C:\users\%username%\file‘

directly .To check through whoami do

l=`whoami`
echo $l
tusharmakkar08
  • 706
  • 1
  • 12
  • 32
  • Thank you for the quick reply. I'll try that out. I've been trying to figure this out for weeks now.... I'm very new to actually programming. – Andrew Davis Jun 28 '13 at 05:10
  • After attempting this for 20 minutes I just now realized you said, "Store it in a variable and then append it to the path name." Finally got this to work. Thank you. – Andrew Davis Jun 28 '13 at 05:33
  • Good to know it worked for you . You need to accept the answer as correct (by clicking on the checkmark below the answer) if it works. – tusharmakkar08 Jun 28 '13 at 05:51
0

Use the %userprofile% variable in your path if you're on Windows:

%userprofile%\Test Source\file.txt
MisterMetaphor
  • 5,900
  • 3
  • 24
  • 31
0

Try:

>>> import getpass
>>> import os.path

>>> usename = getpass.getuser()
>>> mypath = os.path.join("C:\Users", username, "Test Source")
Steve Barnes
  • 27,618
  • 6
  • 63
  • 73