macabeus
macabeus

Reputation: 4572

For what reason when I use environment variables returns error?

I expect both cases returned the same message, but only the first is correct

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

For which reason the second does not handle the ~? How to solve this problem?

Upvotes: 0

Views: 126

Answers (1)

poke
poke

Reputation: 387667

To quote the 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.)

So you can use those functions to perform that expansion:

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

Upvotes: 4

Related Questions