python3 获取文件目录_python3--os.path获取当前文件的绝对路径和所在目录

一.__file__

关于__file__属性,python官方文档的定义是:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute may be missing for certain types of modules, such as C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

翻译:

如果模块是从文件加载的,那么__file__就是文件的路径名。模块是从这个路径加载的。某些类型的模块可能缺少该属性,例如静态链接到解释器的C模块; 对于从共享库动态加载的扩展模块,它是共享库文件的路径名。

说明:

虽然文档说了__file__是文件路径名,但是却没有说是绝对路径还是相对路径。因为模块既可以从绝对路径加载也可以从相对路径加载。所以这个__file__的值可能是绝对路径也可能是相对路径。示例:

如我们在某个模块里新建tests.py文件,文件里面的内容为:

# coding:utf-8

# test.py 打印__file__的值

print(__file__)

运行后可能存在的输出结果:

二.获取当前文件的绝对路径

current_path = os.path.abspath(__file__)

三.获取当前文件所在目录

current_dir = os.path.dirname(os.path.abspath(__file__))

示例:

四.os.path.join()

在前面两步的基础上,可以使用os.path.join()进行路径拼接。

五.参考资料

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值