How do I set the file path to the current user?

那年仲夏 提交于 2019-12-10 14:55:51

问题


Right now for a directory path, I have:

os.chdir(r'C:\users\Ryan\AppData\Local\Google\Chrome\Application')

How do I make it so that instead of "Ryan" it uses the username of the person using the script?


回答1:


Take a look at expanduser of os.path:

os.path.expanduser(path)

On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user‘s home directory.

[..]

On Windows, HOME and USERPROFILE will be used if set, otherwise a combination of HOMEPATH and HOMEDRIVE will be used. An initial ~user is handled by stripping the last directory component from the created user path derived above.

If the expansion fails or if the path does not begin with a tilde, the path is returned unchanged.




回答2:


You can get path with "Ryan" replaced by the current user's name using the following code:

import getpass
path_tpl = 'C:\users\{}\AppData\Local\Google\Chrome\Application'
path = path_tpl.format(getpass.getuser())

But you should probably base your implementation on the data you retrieve from Windows' registry - it is more reliable and the above path will work only on Windows anyways...



来源:https://stackoverflow.com/questions/8734091/how-do-i-set-the-file-path-to-the-current-user

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