Python 读取带有列名的 CSV 项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41567508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:13:56  来源:igfitidea点击:

Read CSV items with column name

pythoncsv

提问by Basj

When reading a CSV, instead of skipping first line (header), and reading row items by number:

读取 CSV 时,不要跳过第一行(标题),而是按数字读取行项目:

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']

where info.csvhas a header line:

其中info.csv有一个标题行:

name;blah
John;Hello2
Mike;Hello2

姓名;废话
约翰;Hello2
Mike;Hello2

回答by e4c5

You are looking for DictReader

您正在寻找DictReader

with open('info.csv') as f:
    reader = csv.DictReader(f, delimiter=';')
    for row in reader:
        name = row['name']
        blah = row['blah']

to quote from the link:

引用链接:

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.

创建一个对象,它的操作类似于常规阅读器,但将读取的信息映射到字典中,其键由可选的 fieldnames 参数给出。... 如果省略 fieldnames 参数,则 csvfile 第一行中的值将用作 fieldnames。

回答by snakecharmerb

You can use a csv.DictReaderinstance to get this behaviour.

您可以使用csv.DictReader实例来获取此行为。

Example from the docs:

文档中的示例:

>>> with open('names.csv') as csvfile:
...     reader = csv.DictReader(csvfile)
...     for row in reader:
...         print(row['first_name'], row['last_name'])
...
Eric Idle
John Cleese

回答by Moses Koledoye

Yes, there is. That's what csv.DictReaderfunction does - supplies the rows as an iterable of dicts.

就在这里。这就是csv.DictReader函数所做的 - 将行作为 dicts 的可迭代对象提供。