Hi
I have a code as given below
def value():
file=open('C:/Documents and Settings/242481/My Documents/file.csv','r')
for line in file:
return "<TOTAL>"+line+"</TOTAL>"
when i execute the script only the first row of the csv file is returned.
how do i get all the rows in the csv file in the for loop.
Thanks in advance : Aadith
That’s because the
returnreturns from the function with the first line on the first iteration through the loop.You could extract the values from
lineon each iteration of the for loop using regular expressions, but it’s a much better idea to just use the thecsvmodule instead of writing your own ad-hoc CSV parser. That means that you don’t have to worry about getting the rules about quoting right, for instance. By way of an example, supposing you want to get the total of all the numbers in the second column, you could do:… although of course you can do anything arbitrarily complex with the values you find in
row[0],row[1], etc. on each iteration of the for loop.Update: In the comment below you ask “is there any way i can execute the return statement as many times as the number of rows in csv file.?”
It sounds as if you might be looking for the
yieldkeyword here. There’s a great explanation of generators andyieldin the question The Python yield keyword explained but to give a brief example of how you might use it in your example, you could do:This will print the product of the second and third column of each row in turn.