jsmith0
jsmith0

Reputation: 1

Reading and Writing CSV files in Python

I am trying to write the first 3 rows of Vehicle Owners.csv onto Speeding Owners.csv along with the 3rd and 4th line of Speeding Vehicles.csv. However, if there is no speeding vehicle to match the Vehicle Owners, the Vehicle Owners go to missing owners.csv

Can someone please explain why this is not working?

Speeding Vehicles.csv looks like this:

GH76GHJ,wallace Street,30,35.0
GH67MNB,wallace Street,30,35.0
GH76GHJ,green street,40,55.9
GH76GJ,green street,40,55.9

Vehicle Owners.csv looks like this:

GH76HJK,1 red street,ross gamble
BH98LOP,1 kings road,muammar gaddafi
CX87YHJ,1 Alison drive,chandler bing
HJ09UJI,6 avenue,idi amin
KI59TOM,7 wall street,robert mugabe

My current code is:

import csv

with open('Vehicle Owners.csv', 'r') as vehicleownersfile:
    owner_reader = csv.reader(vehicleownersfile)
    details = {row[0].lower(): row for row in owner_reader}

with open('Speeding Vehicles.csv', 'r') as speedingvehiclesfile:
    owner_reader = csv.reader(speedingvehiclesfile)

    with open('Speeding Owners.csv', 'w') as speedingownersfile:
        sowriter = csv.writer(speedingownersfile)

        with open('Missing Owners.csv', 'w') as missingownersfile:
            mowriter = csv.writer(missingownersfile)

            for row in owner_reader:
                detail = details.get(row[1].lower())

                if detail is None:
                     mowriter.writerow(row[0], row[1], row[2])
                else:
                     sowriter.writerow(row[0], row[1], row[2], detail[1], detail[2])

Upvotes: 0

Views: 220

Answers (1)

Minijackson
Minijackson

Reputation: 166

I don't exactly know what you are trying to do, but for me, Python (3) shouted that writerow takes 1 argument so I had to replace these lines:

mowriter.writerow(row[0], row[1], row[2])
sowriter.writerow(row[0], row[1], row[2], detail[1], detail[2])

by

mowriter.writerow(row[0:3])
sowriter.writerow(row[0:2] + detail[1:3])

Upvotes: 1

Related Questions