python全局名称';收藏';即使我导入了集合,也没有定义
下面是config.py:python全局名称';收藏';即使我导入了集合,也没有定义,python,function,collections,import,nameerror,Python,Function,Collections,Import,Nameerror,下面是config.py: from collections import OrderedDict def test_config(fileName): tp_dict = collections.OrderedDict() with open("../../config/" + fileName, 'r') as myfile: file_str = myfile.read().replace(' ', '').split('\n') tp_list =
from collections import OrderedDict
def test_config(fileName):
tp_dict = collections.OrderedDict()
with open("../../config/" + fileName, 'r') as myfile:
file_str = myfile.read().replace(' ', '').split('\n')
tp_list = []
for i, x in enumerate(file_str):
x = x.strip()
try:
key = x[:x.index(':')].strip()
value = x[x.index(':')+1:]
if key == 'testpoint':
pass
else:
tp_dict[key] = value.strip().split(',')
except ValueError,e:
pass
if i % 4 == 0 and i != 0:
tp_list.append(tp_dict.copy())
return tp_list
我正在另一个文件test.py中使用该函数:
import config
a = config.test_config('test.txt')
NameError: global name 'collections' is not defined
但是如果我将整个代码从config.py复制粘贴到test.py的顶部,然后使用该函数,那么就没有错误(请参阅下面的代码)。谁能给我解释一下吗?我很困惑。多谢各位
"""
This is test.py
"""
from collections import OrderedDict
def test_config(fileName):
tp_dict = collections.OrderedDict()
with open("../../config/" + fileName, 'r') as myfile:
file_str = myfile.read().replace(' ', '').split('\n')
tp_list = []
for i, x in enumerate(file_str):
x = x.strip()
try:
key = x[:x.index(':')].strip()
value = x[x.index(':')+1:]
if key == 'testpoint':
pass
else:
tp_dict[key] = value.strip().split(',')
except ValueError,e:
pass
if i % 4 == 0 and i != 0:
tp_list.append(tp_dict.copy())
return tp_list
a = test_config('test.txt')
您没有导入名称
集合
,只导入名称OrderedDict
。
因此,您只需使用
bla=OrderedDict()
而不使用模块名称。您不导入集合,只从集合导入。只需编写orderedict
而不是集合。orderedict
将从集合导入orderedict
更改为导入集合选项1:
改变
到
import collections
选项2:
改变
collections.OrderedDict()
到
你说得对。但是为什么它不抱怨test.py中的错误呢?
collections.OrderedDict()
OrderedDict()