How do I read/write files to an unknown user directory?

霸气de小男生 提交于 2019-12-23 21:07:02

问题


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.


回答1:


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



回答2:


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




回答3:


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

%userprofile%\Test Source\file.txt



回答4:


Try:

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

>>> usename = getpass.getuser()
>>> mypath = os.path.join("C:\Users", username, "Test Source")


来源:https://stackoverflow.com/questions/17357554/how-do-i-read-write-files-to-an-unknown-user-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!