开发者

How to specify the current user vairable name in the path to a file

开发者 https://www.devze.com 2023-03-12 10:55 出处:网络
I want to copy a file placed in the folder of the current user logged in. so i have searched how to identify the user that is logged in, so i can point to the user folder in windows.

I want to copy a file placed in the folder of the current user logged in.

so i have searched how to identify the user that is logged in, so i can point to the user folder in windows. for example i want to copy the file "hi.txt" in the Microsoft folder.

"C:\Documents and Settings\john\Application Data\Mic开发者_JS百科rosoft\hi.txt"

so when i move the script to another OS, i want it to identify the relevant user.

so i saw the option :

import getpass

user = getpass.getuser()

so now i want to place the variable "user" instead of pointing to "john" but how can i put a variable in the string of my path?

Thanks in advance, i'm new to programming and new to python.


The home directory of the current user can be expanded using os.path.expanduser(). To open the file "whatever" in the current user's home directory, use

with open(os.path.expanduser("~/whatever")) as f:
    # whatever


The follow codes are copied from python shell, perhaps it can help you.

>>> import getpass
>>> user = getpass.getuser()
>>> user
'yang'
>>> path = "C:\\Documents and Settings\\%s\\Application Data\\Microsoft\\hi.txt" % user
>>> print path
C:\Documents and Settings\yang\Application Data\Microsoft\hi.txt
>>> 

use the % operator.

0

精彩评论

暂无评论...
验证码 换一张
取 消