python获取文件路径(__file__的使用)
前言
在编写python代码的时候,时常会遇上调用文件,如果直接把路径写死,代码是不够灵活的,python提供了__file__来获取文件的路径。
环境说明
-
Windows10 python3.9
使用方法
# 导入os工具包 import os # 获取当前文件所在的位置 # 如果当前文件包含在 sys.path 里面,那么 __file__ 返回一个相对路径 # 如果当前文件不包含在 sys.path 里面,那么 __file__ 返回一个绝对路径(此处我的文件不包含在sys.path中) filepath_1 = __file__ print(filepath_1) # 获取当前文件的绝对路径 filepath_2 = os.path.abspath(__file__) print(filepath_2) # 获取当前文件所在路径的上一层目录 filepath_3 = os.path.dirname(__file__) print(filepath_3) # 获取当前文件上一层目录的绝对路径 filepath_4 = os.path.dirname(os.path.abspath(__file__)) print(filepath_4) # 当前文件的上上层目录的绝对路径 filepath_5 = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print(filepath_5)
结果展示
上述示例的代码,执行结果如下:
D:/testpath/test.py D: estpath est.py D:/testpath D: estpath D:
下一篇:
Pandas分类总结之:分组