读取具有列名称的CSV项目 [英] Read CSV items with column name
问题描述
读取CSV时,不要跳过第一行(标题),而是按数字读取行项目:
When reading a CSV, instead of skipping first line (header), and reading row items by number:
with open('info.csv') as f:
reader = csv.reader(f, delimiter=';')
next(reader, None)
for row in reader:
name = row[0]
blah = row[1]
是否有内置-通过使用标题名称来访问行项目的方法?像这样的东西:
is there a built-in way to access row items by making use of header name? Something like:
with open('info.csv') as f:
reader = csv.reader(f, delimiter=';', useheader=True)
for row in reader:
name = row['name']
blah = row['blah']
其中 info.csv
有标题行:
name; blah
John; Hello2
Mike; Hello2
name;blah
John;Hello2
Mike;Hello2
推荐答案
您正在寻找 DictReader
with open('info.csv') as f:
reader = csv.DictReader(f, delimiter=';')
for row in reader:
name = row['name']
blah = row['blah']
引用链接:
创建一个对象,其功能类似于常规读取器,但将读取的
信息映射到键为gi的dict中取决于可选的
fieldnames参数。
...
如果省略fieldnames参数,则csvfile的
第一行中的值将用作字段名。
Create an object which operates like a regular reader but maps the information read into a dict whose keys are given by the optional fieldnames parameter. ... If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames.
这篇关于读取具有列名称的CSV项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!