You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

导入CSV循环运行仅获最后一行结果,如何修复代码?

解决CSV循环仅输出最后一行的问题

我来帮你分析下问题所在,然后给出修复方案~

你的代码里有两个关键问题导致只输出最后一行:

  • 首先,外层的for line in f:和内层的f.readlines()冲突了。当你第一次进入外层循环时,line会读取文件的第一行,紧接着f.readlines()会一次性把文件剩下的所有行(也就是第二、第三行)都读出来,这时候文件指针已经跳到了文件末尾,外层循环的下一次迭代就没有内容可以读取了。
  • 其次,你每次循环都直接把result变量覆盖成当前行的结果,而不是把所有结果保存下来或者实时输出,所以最后只会保留最后一次循环的赋值。

修复后的代码方案1:直接逐行处理并输出

这种方式更高效,不需要一次性读取所有行到内存里:

import codecs

# 假设你的清理函数是这样的(根据实际情况替换)
def strip_all_entities(text):
    return text

def strip_links(text):
    return text

with codecs.open('test.csv', 'r', 'utf-8') as f:
    # 直接遍历文件的每一行
    for t in f:
        # 去掉每行末尾的换行符和首尾空格,避免多余空白
        cleaned_line = t.strip()
        # 跳过空行(如果有的话)
        if not cleaned_line:
            continue
        # 执行文本清理
        text = strip_all_entities(strip_links(cleaned_line))
        # 生成结果并实时打印
        print(f"{text} : test")

修复后的代码方案2:收集所有结果后统一输出

如果需要后续对结果做进一步处理,可以把结果先存到列表里:

import codecs

def strip_all_entities(text):
    return text

def strip_links(text):
    return text

# 初始化列表来保存所有结果
results = []

with codecs.open('test.csv', 'r', 'utf-8') as f:
    for t in f:
        cleaned_line = t.strip()
        if not cleaned_line:
            continue
        text = strip_all_entities(strip_links(cleaned_line))
        results.append(f"{text} : test")

# 最后统一输出所有结果
for res in results:
    print(res)

这样修改后,就能得到你期望的三行输出啦~

内容的提问来源于stack exchange,提问作者Zayajung C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:51:30