os.path.dirname(__file__)、os.path.abspath(__file__)、os.path.join()使用

转:https://www.jianshu.com/p/a2e603571eba

我在C:\Users\owolf\Desktop目录下写了一个1.py文件,文件代码如下:

import os
#os.path.dirname(__file__)返回的是.py文件的目录
path1=os.path.dirname(__file__)
print(path1)

#os.path.abspath(__file__)返回的是.py文件的绝对路径(完整路径)
path2=os.path.abspath(__file__)
print(path2)

#组合使用
path3=os.path.dirname(os.path.abspath(__file__))
print(path3)

#os.path.join()拼接路径
path4= os.path.join(os.path.dirname(os.path.abspath(__file__)),'1.py')
print(path4)

执行结果如下:

C:/Users/owolf/Desktop
C:\Users\owolf\Desktop\1.py
C:\Users\owolf\Desktop
C:\Users\owolf\Desktop\1.py

相信你已经看出区别了,下面来总结一下:
1、os.path.dirname(file)返回的是.py文件的目录
2、os.path.abspath(file)返回的是.py文件的绝对路径(完整路径)
3、在命令行运行时,如果输入完整的执行的路径,则返回.py文件所在的目录,否则返回空目录。如:

1、不要以命令行的形式来进行os.path.dirname(__file__)这种形式来使用这个函数

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

猜你喜欢

转载自blog.csdn.net/weixin_42205776/article/details/88962740