7

I have created a small Python script to save directories in a side directory, under the current user. I am running on Mac but production is Ubuntu

My problem is the it doesn't manage to identify the dir with the home sign ~

>>> os.path.exists('/Users/partuck/cache_dir/bla')
True
>>> os.path.exists('~/cache_dir/bla')
False
>>> os.system('echo "$USER"')
partuck
0
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Ohad Perry
  • 1,315
  • 2
  • 15
  • 26

2 Answers2

12

From the docs (here, from the glob module):

(For tilde and shell variable expansion, use os.path.expanduser() and os.path.expandvars().)

You want os.path.expanduser().

jedwards
  • 29,432
  • 3
  • 65
  • 92
  • ```os.environ["HOME"] = "/home/cgi/" os.path.expanduser("~/.ssh/id_rsa") ``` worked for me (replace user name) – gies0r May 27 '20 at 20:56
0
os.environ["HOME"] = "/Users/partuck/
os.path.expanduser("~/cache_dir/bla")

(@jedwards answer pointed out expanduser)

gies0r
  • 4,723
  • 4
  • 39
  • 50