使用列nam读取CSV项

2024-06-25 22:34:17 发布

您现在位置:Python中文网/ 问答频道 /正文

读取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]

是否有一种内置的方法通过使用标题名来访问行项目?类似于:

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


Tags: csv项目nameininfo标题foras
3条回答

是的,有。这就是^{}函数所做的-将行作为一个iterable of dicts提供。

你在找DictReader

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

引用链接:

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.DictReader实例来获取此行为。

文档中的示例:

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

相关问题 更多 >