Home > Mobile >  A row is not printed while using the DictReader to read a csv
A row is not printed while using the DictReader to read a csv

Time:12-23

I have created a csv file as below:

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

Now I want to read each row of the csv file with DictRead, but it doesn't read the second line (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

The output is:

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

Now, I have two questions: 1- why it doesn't read the second line of the file and print it out? 2- What if I want to add the restkey to the print command, how can I do that?

Best regards,

CodePudding user response:

When using csv.DictReader, it will read the fieldnames independently before you start reading the file by line, (for row in csv_reader:). There isn't a need to see if you are reading the first line (for fieldnames).

To add the restkey to the print, pop it off the row dictionary and then print the popped value. See 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"]}.')

Prints:

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.
  • Related