WordPress网站建设宣传图片

python os.path.dirname(__file__)

释放双眼,带上耳机,听听看~!

os.path.dirname() 是python os.path 模块的一种方法:

作用:

返回文件路径(只是路径 不包含文件名)

os.path.dirname(path)  # 返回路径path的目录名称
os.path.dirname(__file__)  # 直接返回当前文件路径

os.path.dirname()注意点:

os.path.dirname() 和os.path.basename()、os.path.abspath()的区别

  • os.path.basename()返回的是路径的名称 # 获取文件或者文件夹名称
  • os.path.dirname()返回的是路径目录 # 返回文件或者文件夹的路径
  • os.path.abspath()返回的是绝对路径

os.path.dirname()传入相对路径则返回相对路径 传入绝对路径则返回绝对路径

必须是实际存在的.py文件,如果在命令行执行,则会引发异常NameError: name ‘file’ is not defined,所以不要在命令行已os.path.dirname(__file__)这种形式来使用这个函数

实例代码:

import os.path


# __file__

print(__file__) # 结果为当前文件的绝对路径

path1 = os.path.dirname(__file__)
print(path1)  # 返回当前文件路径

path2 = os.path.dirname('./seoer.txt')
print(path2)  # 返回相对路径

path3 = os.path.dirname('E:\python\seoer.txt')
print(path3)  # 返回绝对路径


更多相关知识:Python3 os.path() 模块 | 菜鸟教程

Python3 os.path() 模块常用方法截图

给TA打赏
共{{data.count}}人
人已打赏
Python内置模块Python笔记

python Queue(进程队列)

2022-1-1 0:13:00

PycharmPython笔记精品资源

PyCharm中文指南、教程-百度云免费

2022-3-1 12:20:33

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索