python零碎知识os.path.dirname(__file__)

import os.path as osp
print osp.dirname(__file__)
如果直接在python console 中或者命令行中运行上面代码,则会报如下错误:

NameError: name '__file__' is not defined

原因是:‘__file__'这个参数代表的是python解释器正在执行的脚本文件,如果直接在命令行运行上面两行代码,则python解释器找不到正在执行的脚本文件,即我们将它写在一个脚本文件中,再在解释器中运行这个脚本文件就ok了

test.py

import os.path as osp
print osp.dirname(__file__)
 
 

然后执行

$ python test.py
$
就会成功输出test.py的路径




猜你喜欢

转载自blog.csdn.net/m0_38082419/article/details/79196386