Trouble copying select rows from one csv to another

Viewed 31

I have a massive csv file with global temperature readings. I want to find all of the rows where the country is United States and append those to a new CSV.

import csv

country = 'United States'

file_in = 'GlobalLandTemperaturesByCity.csv'
file_out = 'out.csv'
country = 'United States'

with open('GlobalLandTemperaturesByCity.csv', 'rt', encoding="utf8") as f, \
    open(file_out, "a", newline='') as f_output:
     reader = csv.reader(f, delimiter=',')
     for row in reader:
         if country == row[4]:
              csv.writer(f_output).writerows(row)

This is what the output csv looks like: one char per cell

1 Answers

You are using writerows() to write one row of data. Try using writerow() instead.

Also, it is better to instantiate your writer outside the for loop once and then use it inside the loop:

writer = csv.writer(f_output)
for row in reader:
    if country == row[4]:
        writer.writerow(row)
Related