I found this example of a simple CSV read / write.
This code reads and writes the CSV file, sorting on the 7th column.
import csv
with open('input.csv', newline='') as csvfile:
rdr = csv.reader(csvfile)
l = sorted(rdr, key=lambda x: x[6], reverse=True)
with open('output.csv', 'w') as csvout:
wrtr = csv.writer(csvout)
wrtr.writerows(l)
The code above outputs a CSV file into output.csv
If I need to do some additional processing other than sorting, I might do it by iterating through the rows of the CSV object. The simplest example exhibiting the problem is just iterating the rows and printing them:
import csv
with open('input.csv', newline='') as csvfile:
rdr = csv.reader(csvfile)
for arow in rdr:
print(arow)
l = sorted(rdr, key=lambda x: x[6], reverse=True)
with open('output.csv', 'w') as csvout:
wrtr = csv.writer(csvout)
wrtr.writerows(l)
The code above prints the CSV rows to the screen as expected. However, the output.csv file is then empty ( 0 bytes)
Why does iteration through the rows cause no output from csv.writer? Is there some type of persistent state in the CSV object that has to be reset?
rdris an iterator. You can only loop through an iterator once. Convert it to a list if you want to process it multiple times.mylist = list(rdr)and using mylist is the solution.