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

来源:互联网 发布:英语视频教学软件 编辑:程序博客网 时间:2024/04/28 07:58

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()使用


0 0
原创粉丝点击