5

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?

Chris
  • 44,602
  • 16
  • 137
  • 156
Ryan Werner
  • 65
  • 3
  • 6

2 Answers2

6

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.

Rob Wouters
  • 15,797
  • 3
  • 42
  • 36
  • +1 Good point. So the solution should be something like: `os.chdir(os.path.expanduseer('~\AppData\Local\Google\Chrome\Application'))`, right? – Tadeck Jan 04 '12 at 23:50
  • @Tadeck, exactly. I'm currently not on Windows so somebody else will have to check, but that is how I do it on Linux. – Rob Wouters Jan 05 '12 at 00:03
  • I am also not on Windows now, so I would be happy to see it confirmed :) For now I assume it is how it will work. – Tadeck Jan 05 '12 at 00:10
1

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

Tadeck
  • 132,510
  • 28
  • 152
  • 198