解决NameError: global name '__file__' is not defined

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhao_5352269/article/details/81632753

在使用线程定时跑Python代码是,获取当前路径的代码

base_dir = os.path.join(os.path.dirname(__file__))

在第二次运行时会提示上面的错误

NameError: global name '__file__' is not defined

经过在查资料找到了两个解决办法

第一个:对代码做如下修改

base_dir = os.path.dirname(os.path.realpath('__file__'))

不过这个为什么加个引号就可以解决这个问题,目前还没有搞懂

第二个:

os.getcwd()

os的getcwd方法也可以获取到当前的目录,实现相同的功能

猜你喜欢

转载自blog.csdn.net/zhao_5352269/article/details/81632753