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()进行路径拼接。

五.参考资料

[1]  关于__file__属性:https://docs.python.org/3/reference/datamodel.html

[2] 关于os.path的操作:https://docs.python.org/3.7/library/os.path.html

猜你喜欢

转载自blog.csdn.net/cckavin/article/details/85392392