6

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
  • 167,268
  • 50
  • 405
  • 846
Ohad Perry
  • 1,105
  • 1
  • 13
  • 25

2 Answers2

11

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
  • 28,237
  • 3
  • 59
  • 86
  • ```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
  • 3,745
  • 1
  • 33
  • 40