Python:关于os.path.isdir,os.path.exists,os.walk无法识别“~/" HOME目录的问题。

在编写Python脚本的时候,我发现,os.path.isdir,os.path.exists,os.walk 根本无法识别 ‘~/‘ 表示的HOME目录。例如:

Python 2.7.12 (default, Jul 18 2016, 10:55:51) 
[GCC 6.1.1 20160621 (Red Hat 6.1.1-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.isdir("~/")
False
>>> os.path.exists("~/")
False
>>> for i in os.walk("~/"):
...     print i
... 
>>> 

但是“ls -l ~/" 却能够正常显示。目前的折中办法是使用os.environ['HOME'] 来获取HOME目录的绝对路径。

>>> HOME=os.environ['HOME']
>>> os.path.isdir(HOME)
True
>>> os.path.exists(HOME)
True
>>> 

 

posted @ 2016-08-07 21:57  nhuang2  阅读(3388)  评论(0编辑  收藏  举报