我期待输出6行,'name'和'timeZone_label'的3个值,但是当我运行嵌套的for循环时,我认为循环只循环一次,它返回3行。我的方法是循环列表FILEDS并获得一个值,然后在字典中使用此值循环并获取列表中的键值。 提前谢谢
path=r'C:\Users\karthik\Desktop\udacity\t1.csv'
with open (path,'r') as p:
reader=csv.DictReader(p)
FIELDS = ["name", "timeZone_label"]
for i in FIELDS:
for row in reader:
print (row[i])
答案 0 :(得分:0)
DictReader
只能遍历csv文件一次,为文件中的每一行返回一个dict。
如果要按列处理数据,则需要使用
多次重新读取文件FIELDS = ["name", "timeZone_label"]
for i in FIELDS:
with open (path,'r') as p:
reader=csv.DictReader(p)
for row in reader:
print (row[i])
或者您需要读取列表中的所有行,并在列表上多次循环使用类似
的内容with open (path,'r') as p:
data = list(csv.DictReader(p))
FIELDS = ["name", "timeZone_label"]
for i in FIELDS:
for row in data:
print (row[i])