Jython CSV连接

Jython CSV连接,jython,Jython,嗨 我有下面给出的代码 def value(): file=open('C:/Documents and Settings/242481/My Documents/file.csv','r') for line in file: return "<TOTAL>"+line+"</TOTAL>" def值(): file=open('C:/Documents and Settings/242481/My Documents/file.csv

嗨 我有下面给出的代码

def value():
    file=open('C:/Documents and Settings/242481/My Documents/file.csv','r')
    for line in file:
        return "<TOTAL>"+line+"</TOTAL>"
def值():
file=open('C:/Documents and Settings/242481/My Documents/file.csv','r')
对于文件中的行:
返回“”+行+“”
当我执行脚本时,只返回csv文件的第一行。 如何在for循环中获取csv文件中的所有行


提前感谢:Aadith

这是因为
返回
在循环的第一次迭代中从函数返回第一行

您可以在for循环的每次迭代中使用正则表达式从
中提取值,但最好使用,而不是编写自己的特殊CSV解析器。例如,这意味着你不必担心引用正确的规则。举个例子,假设您想得到第二列中所有数字的总和,您可以:

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()
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
。。。当然,在for循环的每次迭代中,您可以对
行[0]
行[1]
等中的值执行任意复杂的操作


更新:在下面的评论中,您会问“是否有任何方法可以执行与csv文件中行数相同的返回语句?”

听起来好像你在这里寻找
yield
关键字。问题中对生成器和
yield
有很好的解释,但要给出一个简单的示例,说明如何在示例中使用它,您可以:

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()
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

这将依次打印每行第二列和第三列的乘积。

我要做的是每次从一行中提取数据,然后执行一个代码,代码中的值被参数化。@user619348:我添加了一个示例,演示如何使用CSV模块对第二列中的值求和-但是,您可以对内部循环中的第[0]行、第[1]行等执行任何您喜欢的操作。一旦我运行了测试步骤,包含的代码将从csv文件中提取第一个数据,将值放入步骤并运行一些操作。这个shd适用于csv文件中的所有行。@user619348:是的,我认为这个示例正是您想要的-您只需将
total+=float(row[1])
替换为您所说的“runsomethin”。无论如何,我已经整理了一下我的答案。有什么方法可以让我执行return语句的次数与csv文件中的行数相同吗。?