Because ~/foo
isn't the real path name. (~
is a shortcut that the shell knows)
you need to use
os.path.expanduser("~/foo")
>>> help(os.path.expanduser)
Help on function expanduser in module posixpath:
expanduser(path)
Expand ~ and ~user constructions. If user or $HOME is unknown,
do nothing.