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

Python操作CSV文件时如何让for循环内if语句先于print执行

代码调整方案

原代码核心问题

  • 迭代csv.reader对象时边遍历边打印,目标ID之前的记录会提前输出,且csv.reader是一次性迭代器,遍历完成后无法再次读取全量记录做统一输出
  • 使用r+模式直接写入更新后的记录,只会将内容追加到文件末尾,不会修改原位置的旧记录,会导致文件存在重复冗余记录

修改逻辑

  1. 读取CSV文件时直接将所有记录加载到列表中存储,方便修改、可重复读取
  2. 先遍历列表完成目标员工记录的更新,更新完成后清空原文件,将全量修改后的记录重新写入CSV
  3. 所有更新逻辑执行完毕后,再统一遍历打印所有员工记录

修改后完整代码

import csv

# 生成初始员工CSV文件
with open("Employee.csv", "w", newline='\r\n') as file1:
    empwriter = csv.writer(file1)
    empwriter.writerow(["EmpID.", "Name", "MobNo."])
    n = int(input("How many employee records do you want to add?:"))
    for i in range(n):
        print(f"\nEmployee Record {i+1}")
        empid = input("Enter empID:")
        name = input("Enter Name:")
        mob = input("Enter Mobile No.:")
        empwriter.writerow([empid, name, mob])

# 读取所有记录到列表
with open("Employee.csv", "r", newline='\r\n') as file2:
    empreader = csv.reader(file2)
    all_records = list(empreader)

check = input("\nEnter the empID to check:\n")
opt = int(input('''Which of the following fields do you want to update?:
1.Update the Name
2.Update the Mobile No.
3.Update the whole record\n\n'''))

# 先执行更新逻辑
found = False
for record in all_records:
    if record[0] == check:
        found = True
        if opt == 1:
            newname = input("Enter new name:")
            record[1] = newname
        elif opt == 2:
            newmob = input("Enter new Mobile No.:")
            record[2] = newmob
        elif opt == 3:
            newname = input("Enter new name:")
            newmob = input("Enter new Mobile No.:")
            record[1] = newname
            record[2] = newmob
        print("Record Updated Successfully!\n Updated record:\n", record)
        break
if not found:
    print("未找到对应员工ID的记录")

# 将更新后的全量记录写回CSV
with open("Employee.csv", "w", newline='\r\n') as file3:
    newwriter = csv.writer(file3)
    newwriter.writerows(all_records)

# 统一打印所有记录
for rec in all_records:
    print(rec)

运行上述代码即可得到你期望的输出效果,更新逻辑执行完成后才会统一输出所有员工记录,同时原CSV文件的记录也会被正确修改不会产生冗余数据。

内容的提问来源于stack exchange,提问作者Flash-The-Programmer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 23:06:03