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