最佳答案
我有一个 csv 文件,里面有以下几栏:
身份,姓名,年龄,性别
然后是上面列的大量值。 我试图单独读出列名,然后把它们放在一个列表中。
我使用的是 Dictreader,它给出了正确的详细信息:
with open('details.csv') as csvfile:
i=["name","age","sex"]
re=csv.DictReader(csvfile)
for row in re:
for x in i:
print row[x]
但是我想要做的是,我需要列的列表,(在上面的例子中是“ i”)用输入 csv 自动解析,而不是在列表中硬编码它们。
with open('details.csv') as csvfile:
rows=iter(csv.reader(csvfile)).next()
header=rows[1:]
re=csv.DictReader(csvfile)
for row in re:
print row
for x in header:
print row[x]
这会出现一个错误
Keyerrror:'name'
在行打印行[ x ]中。我哪里出错了? 是否可能使用 Dictreader 获取列名?