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

如何使用for循环重复调用函数 解决CSV读取仅返回最后一行问题

问题根因
  • 你在for循环内部重复定义customer_file()函数,每次循环都会覆盖上一次的函数定义,循环结束后仅保留最后一次循环生成的函数版本
  • Python闭包存在late binding特性:闭包内变量的取值是在函数执行时才查找,而非函数定义时,因此所有函数版本引用的line变量,最终都会指向循环结束时的最后一行值
  • 你仅在循环结束后调用了一次customer_file(),自然只会添加最后一行数据
最优实现方案

直接将整个CSV读取逻辑封装为独立函数,接受文件路径作为入参,返回处理后的字典列表,既没有闭包绑定问题,也方便其他程序复用:

import csv

def read_customer_csv(file_path: str) -> list[dict]:
    customer_list = []
    with open(file_path, 'r', encoding='utf-8') as input_file:
        csv_reader = csv.reader(input_file, delimiter=',')
        # 直接跳过表头,无需判断行号
        next(csv_reader)
        for line in csv_reader:
            customer_list.append({
                'First Name': line[1],
                'Last name': line[2],
                'Age(Years)': int(line[3])
            })
    return customer_list

# 调用示例
my_dic = read_customer_csv('customer.csv')
基于early binding的修改方案(符合你提到的默认参数解决思路)

如果你需要保留循环内定义函数的写法,可以通过默认参数在函数定义阶段就绑定当前行的值,同时要把每次循环生成的函数都保存下来,后续全部调用:

import csv
my_dic = []
func_list = []

with open('customer.csv','r') as input_file:
    csv_reader = csv.reader(input_file, delimiter = ',')
    next(csv_reader)
    for line in csv_reader:
        # 用默认参数实现early binding,定义时就绑定当前line的值
        def customer_file(current_line=line): 
            my_dic.append({
                'First Name': current_line[1],
                'Last name': current_line[2],
                'Age(Years)': int(current_line[3]),
            })
        func_list.append(customer_file)

# 调用所有保存的函数,写入全部行数据
for func in func_list:
    func()

该写法仅用于验证闭包绑定特性,实际开发更推荐上一种独立封装的实现,代码更简洁易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 23:15:09