os.path.dirname(__file__)
作用:返回脚本的路径,
但是需要注意一下几点:
1、必须是实际存在的.py文件,如果在命令行执行,则会引发异常NameError: name '__file__' is not defined
Python 3.6.2 (default, Jun 12 2018, 23:16:48)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>> import os
>>> os.path.dirname(__file__)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
>>> exit()
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文件的绝对路径
总结:
1、不要以命令行的形式来进行os.path.dirname(__file__)这种形式来使用这个函数
2、结合os.path.abspath()使用