为什么我在使用环境变量returns时报错?

For what reason when I use environment variables returns error?

我希望两种情况都返回相同的消息,但只有第一种是正确的

Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.isdir('/home/macabeus/ApenasMeu')
True
>>> os.path.isdir('~/ApenasMeu')
False

为什么第二个不处理~?如何解决这个问题?

引用os.path module documentation

Unlike a unix shell, Python does not do any automatic path expansions. Functions such as expanduser() and expandvars() can be invoked explicitly when an application desires shell-like path expansion. (See also the glob module.)

因此您可以使用这些函数来执行该扩展:

>>> os.path.expanduser('~/ApenasMeu')
'/home/macabeus/ApenasMeu'
>>> os.path.isdir(os.path.expanduser('~/ApenasMeu'))
True