4

At some point the tilde symbol ~ was no longer recognized as my home directory, only in Python. ~ still works with in terminal, so I'm not sure what happened but any insight on how to fix it you will save me some typing thanks!

On macOs Mojave

import os
tilde = '~'
print(os.path.exists(tilde))
os.system("if test -d ~; then echo 'exists'; fi")

OUTPUT:

False
exists
buzz11
  • 89
  • 7
  • 1
    The tilde is a shortcut recognized by your shell, not an alternate name for your home directory. – chepner Nov 28 '18 at 19:17

2 Answers2

5

The ~ is interpreted by the OS, not Python. The way to use it from Python script is:

from os.path import expanduser
home = expanduser("~")

now home will have the path denoted by ~

handras
  • 1,548
  • 14
  • 28
AbtPst
  • 7,778
  • 17
  • 91
  • 172
4

You have to use os.path.expanduser on the path first. Try

print(os.path.exists(os.path.expanduser(tilde)))

instead.

holdenweb
  • 33,305
  • 7
  • 57
  • 77