即使我导入了集合,也没有定义 python 全局名称 'collections'

标签 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 = []
    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')

最佳答案

from collections import OrderedDict 更改为 import collections

关于即使我导入了集合,也没有定义 python 全局名称 'collections',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28031880/

相关文章:

jQuery : call a function with a String Variable

scala - 为什么 Scala 并行集合有时会导致 OutOfMemoryError?

python - Django : Page not found (404) Why. ..?

python - 如何在窗口坐标内插入一个带有数字的圆圈?

python - 从另一个 Python 文件执行函数时遇到问题

c - 如何在 C 中重命名/别名函数?

collections - 使用 cql3 在 cassandra 中更新 map

java - 用单个对象的克隆填充数组

python - 从 Python 的字典中压缩两个值

python - 有没有办法从 Enter 键读取按键?