如何在 python 中提取 csv 中的列

How to extract the column in csv in python

我正在使用 python 和 csv 库以及 Tkinter GUI

Column1    Column2
Test1      ID1
           ID2
           ID3
Test2      Act1
           ACT2
           ACT3

我想根据第 1 列测试编号显示第 2 列。
例如:SO Test1 is selected ID1 , ID2, ID3 should be shown and in next iteration When Test2 is selected Act1, Act2, Act3 is showed

我尝试了什么:

with open('Test.csv') as f:
  listbox = tk.Listbox(self.root, width=162, height=200)
  listbox.place(x=10, y=50)
  reader = csv.DictReader(f, delimiter=',')
  for row in reader:
    adata1 = row['column1']
    adata2 = row['column2']

    if adata1 != adata1 or adata1 == "":
      listbox.insert('end', adata2)
    else:
      continue

如果有人可以帮助我,请。

据我了解,Test.csv文件的内容是这样的:

column1,column2
Test1,ID1
,ID2
,ID3
Test2,ACT1
,ACT2
,ACT3

然后可以用字典来存储CSV文件内容:

import csv

tests = {}
with open('Test.csv') as f:
    reader = csv.DictReader(f, delimiter=',')
    for row in reader:
        if row['column1']:
            key = row['column1']
            tests[key] = []
        tests[key].append(row['column2'])

tests 的结果将是:

{'Test1': ['ID1', 'ID2', 'ID3'], 'Test2': ['ACT1', 'ACT2', 'ACT3']}

并且您可以根据您选择的键将所需的项目填充到 listbox 中:

listbox = tk.Listbox(self.root, width=162, height=200)
listbox.place(x=10, y=50)

...

key = 'Test1' # assume Test1 is selected as the key

listbox.delete(0, 'end')
for item in tests[key]:
    listbox.insert('end', item)