【问题标题】:A row is not printed while using the DictReader to read a csv使用 DictReader 读取 csv 时不打印一行
【发布时间】:2022-01-23 21:44:39
【问题描述】:

我创建了一个 csv 文件,如下所示:

%%writefile employee2.csv
name, department, birthday month
John Smith, Accounting, November, 6
Erica Meyers, IT, March

现在我想用 DictRead 读取 csv 文件的每一行,但它不读取第二行 (John Smith)

import csv
with open('employee2.csv', newline='') as csv_file:
    csv_reader = csv.DictReader(csv_file, restkey='day', skipinitialspace=True)
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are: {", ".join(row)}')
        else:
            print(f'{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.')
        line_count += 1

输出是:

Column names are: name, department, birthday month, day
Erica Meyers works in the IT department, and was born in March.

现在,我有两个问题: 1-为什么它不读取文件的第二行并打印出来? 2- 如果我想在打印命令中添加restkey,我该怎么做?

最好的问候,

【问题讨论】:

    标签: python csv


    【解决方案1】:

    当使用csv.DictReader时,它会在你开始逐行读取文件之前独立读取fieldnames,(for row in csv_reader:)。无需查看您是否正在阅读第一行(fieldnames)。

    要将restkey 添加到打印中,pop 将其从行字典中删除,然后打印弹出的值。见this

    import csv
    with open('tmp1.csv', newline='') as csv_file:
        csv_reader = csv.DictReader(csv_file, restkey='day', skipinitialspace=True)
        cols = csv_reader.fieldnames
        print('Column names are: ', cols)
        for row in csv_reader:
            day = row.pop('day', None)
            if day != None:
                print(f'{row["name"]} works in the {row["department"]} department, and was born on {row["birthday month"]} {day[0]}.')
            else:
                print(f'{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.')
    

    打印:

    Column names are:  ['name', 'department', 'birthday month']
    John Smith works in the Accounting department, and was born on November 6.
    Erica Meyers works in the IT department, and was born in March.
    

    【讨论】:

    • 非常感谢您的解释。
    猜你喜欢
    • 1970-01-01
    • 2018-04-17
    • 2015-12-10
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    相关资源
    最近更新 更多