0

我目前正在编写一个 python 脚本来分析 SNMP 数据。我有一个读取 csv 文件并在 CheckListBox 中组织的 CheckBoxes 中显示标题的函数。我想删除第一项,但这样做会导致我的 CheckListBox 不会填充,我无法弄清楚原因。这是代码:

#Generates CheckBoxList with fields from csv (first row)
def onSNMPGen(self,e):
    #reads in first row of csv file; this snmpPaths[0] will likely cause issues with multiple paths -- fix later
    listItems = []
    print "*** Reading in ", self.snmpPaths[0], "....."
    with open(self.snmpPaths[0], 'r') as f: #remember to close csv
        reader = csv.reader(f)
        print "*** Populating Fields ..... "
        for row in reader:
            #Inserts each field into CheckListBox as an item;
            #self.SNMPCheckListBox.InsertItems(row,0)
            listItems.append(row)
            break
        f.close()
    #Need to remove 'Time' (first item) from listItems
    #listItems.pop(0) # this makes it so my CheckListBox does not populate
    #del listItems[0] # this makes it so my CheckListBox does not populate
    for key in listItems:
        self.SNMPCheckListBox.InsertItems(key,0)
4

2 回答 2

0
 for row in reader:
            #Inserts each field into CheckListBox as an item;
            #self.SNMPCheckListBox.InsertItems(row,0)
            listItems.append(row)
            break

因为您使用了 break,所以您的列表将只有一项。因此,当您删除该项目时,您的 CheckListBox 中没有任何内容可以填充。

如果您 100% 确定它是第一项,那么您可以像这样重写循环:

 for row in reader[1:]:
            #Inserts each field into CheckListBox as an item;
            #self.SNMPCheckListBox.InsertItems(row,0)
            listItems.append(row)

reader[1:] 意味着您只会在 listItems 列表中添加第二个项目。

于 2015-04-07T14:48:01.453 回答
0

感谢 roxan,我在看到我的错误后能够解决我的问题。我将 csv 行作为一个项目存储在列表中,而不是将该行的每一列作为一个项目。这是我的修复:

#Generates CheckBoxList with fields from csv (first row)
def onSNMPGen(self,e):
    #reads in first row of csv file; this snmpPaths[0] will likely cause issues with multiple paths -- fix later
    listItems = []
    print "*** Reading in ", self.snmpPaths[0], "....."
    with open(self.snmpPaths[0], 'r') as f: #remember to close csv
        reader = csv.reader(f)
        print "*** Populating Fields ..... "
        for row in reader:
            listItems = row             break
        f.close()
    del listItems[0] #Time is always first item so this removes it
    self.SNMPCheckListBox.InsertItems(listItems,0)
于 2015-04-07T15:09:43.293 回答