python中的os.path.dirname(__file__)的使用

os.path.dirname(path)

语法:os.path.dirname(path)
功能:去掉文件名,返回目录
如:

print(os.path.dirname("E:/Read_File/read_yaml.py"))
#结果:
E:/Read_File

print(os.path.dirname("E:/Read_File"))
#结果:
E:/

os.path.dirname(__file__)

print(__file__) #结果 E:/Read_File/read_yaml.py

__file__表示了当前文件的path

若print os.path.dirname(file)所在脚本是以绝对路径运行的,则会输出该脚本所在的绝对路径,若以相对路径运行,输出空目录

os.path.dirname(__file__)返回脚本的路径,但是需要注意一下几点:

1、必须是实际存在的.py文件,如果在命令行执行,则会引发异常NameError: name '__file__' is not defined

2、在运行的时候如果输入完整的执行的路径,则返回.py文件的全路径如:

python c:/test/test.py 则返回路径 c:/test ,如果是python test.py 则返回空

3、结合os.path.abspath用,效果会好,如果大家看过一些python架构的代码的话,会发现经常有这样的组合

os.path.dirname(os.path.abspath(__file__)),os.path.abspath(__file__)返回的是.py文件的绝对路径

这就是os.path.dirname(__file__)的用法,其主要总结起来有:
1、不要已命令行的形式来进行os.path.dirname(__file__)这种形式来使用这个函数

2、结合os.path.abspath()使用

参考:

https://blog.csdn.net/weixin_38470851/article/details/80367143

https://blog.csdn.net/u011760056/article/details/46969883

猜你喜欢

转载自www.cnblogs.com/wind666/p/10888745.html