Python OS包

os.path基本用法

  • os.path.abspath(path)

    返回path 的绝对路径

  • os.path.dirname(path)

    返回path所在的路径

下面举个例子来说明:

有一个文件config.py,所在的路径是/home/work/web_app/config_files/,文件内容为:

import os
a = os.path.abspath(__file__)
b = os.path.dirname(a)
c = os.path.dirname(b)
print a
print b
print c

打印出来的内容为:

/home/work/web_app/config_files/config.py
/home/work/web_app/config_files
/home/work/web_app

如何获取当前用户的根目录

>>> from os.path import expanduser
>>> home = expanduser("~")
>>> home
'/Users/yangle'
>>> type(home)
<type 'str'>

获取某个路径下的所有文件名

import os
for filename in os.listdir(package_dir):
    print(os.path.join(package_dir, filename))