python获取文件的绝对路径

文件目录结构如下:


第一种方法:

os.path.abspath(__file__)

假设app.py中想读取config.ini文件的内容,首先app.py需要知道config.ini的文件路径,从目录结构上可以看出,config.ini与app.py的父目录同级,也就是获取到app.py父目录(bin文件夹的路径)的父目录(config文件夹路径)的绝对路径再拼上config.ini文件名就能获取到config.ini文件

首先,在app.py中测试一下:

import os

def load_file():
    # 获取当前文件路径
    current_path = os.path.abspath(__file__)
    # 获取当前文件的父目录
    father_path = os.path.abspath(os.path.dirname(current_path) + os.path.sep + ".")
    # config.ini文件路径,获取当前目录的父目录的父目录与congig.ini拼接
    config_file_path=os.path.join(os.path.abspath(os.path.dirname(current_path) + os.path.sep + ".."),'config.ini')
    print('当前目录:' + current_path)
    print('当前父目录:' + father_path)
    print('config.ini路径:' + config_file_path)


load_file()


输出结果:

当前目录:/Users/shanml/Documents/python/config/bin/app.py
当前父目录:/Users/shanml/Documents/python/config/bin
config.ini路径:/Users/shanml/Documents/python/config/config.ini
从结果中可以看到一切都正常,没有什么问题,假如现在需要从main.py中执行app.py的load_file()方法呢?

来测试一下:

main.py

from bin.app import load_file

if __name__=='__main__':
    load_file()


输出结果,路径同样没问题:

当前目录:/Users/shanml/Documents/python/config/main.py
当前父目录:/Users/shanml/Documents/python/config
config.ini路径:/Users/shanml/Documents/python/config.ini

参考:https://www.cnblogs.com/yajing-zh/p/6807968.html


第二种方法:

使用inspect

app.py:

import os,inspect


def load_file():
    # 获取当前文件路径
    current_path=inspect.getfile(inspect.currentframe())
    # 获取当前文件所在目录,相当于当前文件的父目录
    dir_name=os.path.dirname(current_path)
    # 转换为绝对路径
    file_abs_path=os.path.abspath(dir_name)
    # 划分目录,比如a/b/c划分后变为a/b和c
    list_path=os.path.split(file_abs_path)
    print('list_path:' + str(list_path))
    # 配置文件路径
    config_file_path=os.path.join(list_path[0],'config.ini')
    print('当前目录:' + current_path)
    print('config.ini文件路径:' + config_file_path)


在app.py中执行load_file()方法:

list_path:('/Users/shanml/Documents/python/config', 'bin')
当前目录:/Users/shanml/Documents/python/config/bin/app.py
config.ini文件路径:/Users/shanml/Documents/python/config/config.ini

在mian.py中执行load_file方法:

list_path:('/Users/shanml/Documents/python/config', 'bin')
当前目录:/Users/shanml/Documents/python/config/bin/app.py
config.ini文件路径:/Users/shanml/Documents/python/config/config.ini

参考: https://xnow.me/programs/python.html







猜你喜欢

转载自blog.csdn.net/lom9357bye/article/details/79285170