我在列出当前用户的主目录时遇到问题而不知道它的绝对路径。我尝试了以下内容,但它不起作用:
[root@blackbox source]# python
Python 2.6.6 (r266:84292, Dec 7 2011, 20:38:36)
[GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.listdir('/root')
['python', '.bashrc', '.viminfo']
>>> os.listdir('~')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory: '~'
>>>
答案 0 :(得分:14)
您需要使用os.path.expanduser()
function:
>>> import os.path
>>> os.path.expanduser('~')
'/home/username'
答案 1 :(得分:1)
你可以问这样的操作系统:
>>> import os
>>> os.environ['HOME']
'/home/noctua'
>>> os.listdir(os.environ['HOME'])