Here's an example of the contents of my CSV file:
Fruit, colour, ripe,
apple, green,,
banana, yellow,,
pineapple, green,,
plum, purple,,
I want to loop through the contents of the CSV file and according to a test (extrinsic to the CSV data, using an input value supplied to the enclosing function), end up with something like this:
Fruit, colour, ripe,
apple, green, true,
banana, yellow,,
pineapple, green,,
plum, purple, true,
My current code looks like this:
csv_data = csv.reader(open('./data/fruit_data.csv', 'r'))
for row in csv_data:
fruit = row[0]
if fruit == input:
# Here, write 'true' in the 'ripe' column.
It's easy enough to add new data in one go, using the CSV module or pandas
, but here I need to add the data iteratively. It seems that I can't change the CSV file in place(?), but if I write out to a different CSV file, it's going to overwrite on each match within the loop, so it'll only reflect that value.