我对这个代码有问题。虽然名字错误似乎很普遍,但我无法通过搜索找到解决方法。这是密码。。。在
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'
回溯。。。。在
^{pr2}$此函数是从main()调用的,但我不明白为什么“DataPlotLoc”是一个全局名称,因为它在这个函数中。不管怎样,我想我错过了一句话来定义它,但是我不知道如何和在哪里。我很想得到帮助。在
编辑: 为了增加更多的信息,DataPlotLoc是插入代码时列表的名称,即DataPlotLoc=[['a','b','c',…..]]并且它起作用了。线 plotOrig=DataPlotLoc[int(in_Sel)+1]引用此列表,但显然它现在被读入csv.reader所以现在我不确定如何分配这个变量。 我假设在确认用户是否输入'q'后,我仍然需要它接受一个整数,+1将添加到输入的数字中,以便它与从列表中选择的相应行项目的正确索引号对齐。 抱歉,如果这有点混乱,但我自己也有点困惑。。。在
好吧,正如错误消息所说,您在定义它之前使用了
DataPlotLoc
。如果你搜索你的代码,你会发现它从来没有被定义过。如果你不知道你想说什么,我就不能回答更多的问题了。在Python假设您指的是该名称的全局变量,因为您从未给它分配任何东西,这会使它成为局部变量。在
Python之所以说
global name ... not defined
,是因为它在函数体中没有看到对DataPlotLoc
的任何赋值,所以它假设它必须是一个全局变量,但在那里找不到它。(见下面阿巴内特的评论)根据代码判断,我想您希望
DataPlotLoc
包含从MonPlotDb.csv
提取的信息,在这种情况下,您需要做两件事:(A)初始化
DataPlotLoc
(B)在循环和打印选项时,将值附加到
^{pr2}$DataPlotLoc
。在我不知道为什么要在
plotOrig = DataPlotLoc[int(in_Sel) + 1]
的行中添加一个,我认为您可以将csv.reader
行简化为下面的csv.reader(csvfile)
(我认为带逗号的excel是默认行为)编辑:要从CSV的每一行提取一列,请将B部分中的代码改为如下所示:
相关问题 更多 >
编程相关推荐