os.path.abspath(__file__)&os.path.dirname()&os.path.basename(__file__)&os.path.join()的用法详解

os.path.用法详解

os.path.abspath(__file__)

os.path.dirname(__file__):返回脚本的绝对路径

import os

print(os.path.abspath(__file__))
D:\Python\PycharmProjects\pythonProject\crawl\os.path.测试.py
  • 不可以直接在命令行/JupyterNotebook中运行该文件, 否则会报错 "NameError: name '__file__' is not defined"

os.path.dirname()

os.path.dirname():返回当前脚本文件的所在路径(上一层目录)

import os

# 返回脚本绝对路径
print(os.path.abspath(__file__))
# 返回脚本上两层目录路径
root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(root_path)
D:\Python\PycharmProjects\pythonProject\crawl\os.path.测试.py
D:\Python\PycharmProjects\pythonProject

os.path.basename(__file__)

import os

# 返回脚本的文件名称
print(os.path.basename(__file__))
os.path.测试.py

os.path.join()

os.path.join():拼接路径,与上面组合使用:

import os

runpyp = os.path.abspath(__file__)  # 返回当前脚本文件的绝对路径
modeldirp = os.path.dirname(runpyp)  # 返回当前脚本文件的所在路径(上一层目录)
modelp = os.path.join(modeldirp, "model_6_4_0.9085.h5")  # 拼接路径
print(runpyp)
print(modeldirp)
print(modelp)
D:\Python\PycharmProjects\pythonProject\crawl\os.path.测试.py
D:\Python\PycharmProjects\pythonProject\crawl
D:\Python\PycharmProjects\pythonProject\crawl\model_6_4_0.9085.h5

参考Link Link


加油!

感谢!

努力!

上一篇:linux下将qt打包为可执行文件


下一篇:Git