开发者

Jython CSV connection

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 return returns from the function with the first line on the first iteration through the loop.

You could extract the values from line on each iteration of the for loop using regular expressions, but it's a much better idea to just use the the csv module 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:

import csv

def total_of_second_column():
    total = 0.0
    fp = open('C:/Documents and Settings/242481/My Documents/file.csv')
    try:
        cr = csv.reader(fp)
        for row in cr:
            total += float(row[1])
        return total
    finally:
        fp.close()

... 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 yield keyword here. There's a great explanation of generators and yield in 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:

def two_column_products():
    fp open('C:/Documents and Settings/242481/My Documents/file.csv')
    try:
        cr = csv.reader(fp)
        for row in cr:
            yield float(row[1]) * float(row[2])
    finally:
        fp.close()

for result in two_column_products():
    print "got result:", result

This will print the product of the second and third column of each row in turn.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜