Answers for "python read a csv dictreader"

38

csv python write

import csv

with open('names.csv', 'w') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
Posted by: Guest on March-10-2020
0

accessing elements in DictReader

import csv

input_file = csv.DictReader(open("people.csv"))

max_age = None
oldest_person = None
for row in input_file:
    age = int(row["age"])
    if max_age == None or max_age < age:
        max_age = age
        oldest_person = row["name"]

if max_age != None:
    print "The oldest person is %s, who is %d years old." % (oldest_person, max_age)
else:
    print "The file does not contain any people."
Posted by: Guest on October-21-2020

Python Answers by Framework

Browse Popular Code Answers by Language