Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 960
Ryan Werner Avatar asked Jan 04 '12 21:01

Ryan Werner


Video Answer


2 Answers

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.

like image 105
Rob Wouters Avatar answered Sep 21 '22 06:09

Rob Wouters


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

like image 21
Tadeck Avatar answered Sep 21 '22 06:09

Tadeck