我是 Python 的业余爱好者,我确信有一个简单的解决方案。我正在尝试调用一个使用 os.path.exists 函数的模块。如果我像下面这样写,代码运行正常。
import os
if os.path.exists('text.txt'):
print 'yes'
但是,当我如下调用模块时,出现此错误:“NameError: global name 'os' is not defined” -
import os
import modutest
modutest.test()
有了这个模块,(我称之为 modutest.py)
def test():
if os.path.exists('text.txt'):
print 'yes'
最佳答案
只需在 modutest.py 中导入 'os' 模块,如下所示:
import os
def test():
if os.path.exists('text.txt'):
print 'yes'
modutest.py 是完全不同的文件,因此您必须导入“os”模块。
关于调用模块后不再定义 Python 全局名称 'os',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16760652/