os.path.dirname(__file__)返回脚本的路径,但是需要注意一下几点:
必须是实际存在的.py文件,如果在命令行执行,则会引发异常NameError: name \'__file__\' is not defined
在运行的时候如果输入完整的执行的路径,则返回.py文件的全路径如:python c:/test/test.py 则返回路径 c:/test ,如果是python test.py 则返回空。
结合os.path.abspath用,效果会好,如果大家看过一些python架构的代码的话,会发现。
经常有这样的组合:
os.path.abspath(os.path.dirname(__file__))
os.path.dirname(os.path.abspath(__file__))
返回的是.py文件的绝对路径,这就是os.path.dirname(__file__)的用法,其主要总结起来有:
1、不要已命令行的形式来进行os.path.dirname(__file__)这种形式来使用这个函数
2、结合os.path.abspath()使用1