NameError...global not defined



我对这段代码有问题。虽然名称错误似乎很普遍,但我无法通过搜索找到修复方法。下面是代码…

def fmp_sel():
    with open ('MonPlotDb.csv', 'rU') as csvfile: 
            next(csvfile, None)
            fmpList = csv.reader(csvfile, delimiter=',', dialect=csv.excel_tab)
            for item in enumerate(fmpList):
                    print "[%d] %s" % (item)
    while True:
        try:
            in_Sel = raw_input(('''Choose from list or 'q' to quit:'''))                                               
             if in_Sel == 'q':
                print 'Quit?'                                           
                conf = raw_input('Really? (y or n)...')    
                if conf == 'y':                                              
                    print 'Seeya!'                                        
                    break
                else:
                    continue                                                        
             plotOrig = DataPlotLoc[int(in_Sel) + 1]                              
            print 'You selected', plotOrig[1]                
            break
        except (ValueError, IndexError):
            print 'Error: Try again'

和回溯....

File "E:FireRegDbRec_2012dblist_outonly.py", line 28, in fmp_sel  
plotOrig = DataPlotLoc[int(in_Sel) + 1]                             
NameError: global name 'DataPlotLoc' is not defined

这个函数正在从main()调用,但我看不出为什么'DataPlotLoc'是一个全局名称,因为它在这个函数内。不管怎样,我想我漏掉了一条线来定义它,但我不知道怎么定义,在哪里定义。我需要一些帮助。

编辑:只是补充一些信息…'DataPlotLoc'是将列表插入代码ie时的名称。DataPlotLoc=[['a', 'b', 'c',.... .它成功了。这条线plotOrig = DataPlotLoc[int(in_Sel) + 1]引用这个列表,但显然它现在正在被csv读入。所以现在我不确定如何分配这个变量。我假设在确认用户是否输入'q'之后,仍然需要它接受一个整数,并且+1是要添加到输入的数字上,以便它与从列表中选择的相应行项的正确索引号保持一致。

那么,正如错误消息所说,您在定义DataPlotLoc之前使用了它。如果你搜索你的代码,你会发现它在任何地方都没有定义。在不知道你的意思的情况下,我无法回答更多的问题。

Python认为您指的是该名称的全局变量,因为您从未为其赋值任何内容,这会使其成为一个局部变量。

Python说global name ... not defined是因为它在函数体中没有看到任何对DataPlotLoc的赋值,所以它假设它必须是一个全局变量,并且没有在那里找到它。(见下面abarnett的评论)

根据您的代码判断,我认为您希望DataPlotLoc包含从MonPlotDb.csv提取的信息,在这种情况下,您需要做两件事:

(A) Initialize DataPlotLoc

def fmp_sel():
    DataPlotLoc = []  # <-----------------!!!!
    with open ('MonPlotDb.csv', 'rU') as csvfile:

(B)在循环和打印选项时,将值附加到DataPlotLoc

    next(csvfile, None)
    fmpList = csv.reader(csvfile, delimiter=',', dialect=csv.excel_tab)
    for item in enumerate(fmpList):
        DataPlotLoc.append(item[1])  # <---------!!!
        print "[%d] %s" % (item)

我不知道为什么你在plotOrig = DataPlotLoc[int(in_Sel) + 1]的行中添加一个,我认为你可以将csv.reader行简化为以下csv.reader(csvfile)(我认为excel带逗号是默认行为)

Edit:要从CSV的每行中只提取一列,请将B部分中的代码更改为如下内容:

    next(csvfile, None)
    fmpList = csv.reader(csvfile, delimiter=',', dialect=csv.excel_tab)
    for item in enumerate(fmpList):
        i, data = item  # enumerate returns tuples of the form (i, data)
        vals = (i, data[1])  # <----- put in the proper index of the column
        DataPlotLoc.append(vals)
        print "[%d] %s" % vals  # <--- assuming  you want to change the print as well

最新更新