Cat*_*ine 4 python collections import function 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 = []
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
Run Code Online (Sandbox Code Playgroud)
我在另一个文件test.py中使用该函数:
import config
a = config.test_config('test.txt')
NameError: global name 'collections' is not defined
Run Code Online (Sandbox Code Playgroud)
但是,如果我将整个代码从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')
Run Code Online (Sandbox Code Playgroud)
小智 5
选项 1: 更改
from collections import OrderedDict
Run Code Online (Sandbox Code Playgroud)
到
import collections
Run Code Online (Sandbox Code Playgroud)
选项2:
改变
collections.OrderedDict()
Run Code Online (Sandbox Code Playgroud)
到
OrderedDict()
Run Code Online (Sandbox Code Playgroud)