I want to be able to use Python to open a .csv file like this:
5,26,42,2,1,6,6
and then perform some operation on them like addition.
total = 0
with open("file.csv") as csv_file:
for row in csv.reader(csv_file, delimiter=','):
for number in range(7):
total += int(row[number])
The problem is that since the .csv file only has one row and an unknown number of columns, I don’t know how to make this work without either hard-coding it like or using really ugly code.
Is there any way of looping through the columns using something like for columns in file in Python?
You can just say
For example:
The reason why you can do this is that csv.reader returns a simple list for every row, so you can iterate over it as you would any other list in Python.
However, in your case, since you know that you have a file with a single line of comma-separated integers, you could make this much simpler: