os.path.abspath(__file__)与os.path.dirname()以及os.path.basename(__file__)的用法详解

1、os.path.abspath(_file_)

  • os.path.dirname(_file_) 返回脚本的绝对路径
  • 不可以直接在命令行运行该文件, 否则会报错 “NameError: name '__file__' is not defined”
  • 可直接运行该文件或者调用该文件也可以
1.1、在 D:\xxxx\xx\util 路径下建立test.py文件如下:
import os
# 返回脚本绝对路径
print(os.path.abspath(__file__))
1.2、在cmd中运行该文件,得结果如下:

在这里插入图片描述

2、os.path.dirname()

  • os.path.dirname(path) 返回path的父路径
  • 可嵌套使用,如 os.path.dirname(os.path.dirname(path) ) 返回父路径的父路径
  • 可以 os.path.abspath(_file_) 联合使用
2.1、在 D:\xxxx\xx\util 路径下建立test.py文件如下:
import os
# 返回脚本绝对路径
print(os.path.abspath(__file__))
# 返回脚本上两层目录路径
root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(root_path)
2.2、在cmd中运行该文件,得结果如下:

在这里插入图片描述

3、os.path.basename(_file_)

  • os.path.basename(_file_) 返回脚本的文件名称
  • 不可以直接在命令行运行该文件, 否则会报错 “NameError: name '__file__' is not defined”
  • 可直接运行该文件或者调用该文件也可以
3.1、在 D:\xxxx\xx\util 路径下建立test.py文件如下:
import os
# 返回脚本的文件名称
print(os.path.basename(__file__))
3.2、在cmd中运行该文件,得结果如下:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43404784/article/details/88994350