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







  • 12
    点赞
  • 73
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值