I have been experimenting with writing to a csv file lately and stumbled across a problem. I have a for loop running through a list of items, and would like to rewrite this list in a .csv file, with each element of the list being in a new row. So, I structured the code as follows.
import csv
groceries = ["banana", "apple", "orange", "orange", "milk", "orange",
"banana"]
file_name = "an_example_file_here"
banana_count = 0
apple_count = 0
orange_count = 0
milk_count = 0
for i in groceries :
w = csv.writer(open(file_name + ".csv", "w")) #writing to .csv
if i == "banana":
banana_count += 1
w.writerow(["banana"])
elif i == "apple":
apple_count += 1
w.writerow(["apple"])
elif i == "orange":
orange_count += 1
w.writerow(["orange"])
elif i == "milk":
milk_count +=1
w.writerow(["milk"])
w.writerow(["banana_count = ", str(banana_count)],)
w.writerow(["apple_count = ", str(apple_count)],)
w.writerow(["orange_count = ", str(orange_count)],)
w.writerow(["milk_count = ", str(milk_count)],)
I expected to get a csv file looking something like: banana, apple, orange, orange, milk, orange, banana, banana_count = 2, apple_count = 1, orange_count = 3, milk_count = 1
But, the actual file I am getting looks like: banana, banana_count = 2, apple_count = 1, orange_count = 3, milk_count = 1
I am not sure why, any help appreciated. Thank you!