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

2019-06-23 01:40发布

问题:

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