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

如何用Python给CSV指定行追加数据并移至另一个CSV文件

CSV目标行迁移与数据追加实现方案

需求说明

基于用户输入的车牌号定位Cars.csv中的目标车辆行,为该行追加销售相关数据后,将该行移动到另一个CSV文件(如SoldCars.csv),并从原Cars.csv中删除该行。

现有代码片段

1. 车牌号搜索代码

import csv

found = False
while found == False:
  reg = input("\nEnter the registration number of the car sold\n")
  with open("Cars.csv") as sale:
    file = csv.reader(sale)
    for i in file:
      if i[2] == reg:
        found = True 
  if found != True:
    print("\nRegistration not found, please try again\n")
# 注:with块结束后文件已自动关闭,此处sale.close()多余

2. 新车写入Cars.csv代码

if Choice1==1 and role==1:#buy a car
  confirm="n"
  while confirm!="y":
    fileopen = open("Cars.csv","a", newline="")
    file = csv.writer(fileopen)
    buyer=input("\nWhat is your name?\n")
    brand=input("\nWhat brand made the car?\n")
    colour=input("\nWhat colour is the car?\n")
    reg=input("\nWhat is the car's registration number?\n")
    broughtfor=input("\nHow much did the car cost?\n")
    date=input("\nWhat date was the car brought on?\n")
    data=[brand,colour,reg,broughtfor,date,buyer]
    # 数据已整理为列表
    confirm=input("Are you sure this information is correct\ny/n\n")# 确认提示
    if confirm=="y":
      file.writerow(data)# 确认后写入文件
    if confirm != "y":
      Choice2=int(input("\nWould you like to:\n 1) Re-enter the information\n 2) Exit to the menue\n")) # 允许重新输入或返回菜单
      if Choice2==2:
        confirm="y" # 取消输入
  fileopen.close()
  print("Thank you\n")

3. 销售数据输入代码(需追加的内容)

name=input("\nPlease enter your name\n")
price=int(input("\nHow much did this car sell for?\n"))
date=input("\nWhat date was the car sold?\n")
data=[price, date, name]

解决方案实现步骤

  1. 改进搜索逻辑:找到目标行时,保存该行的完整数据,而非仅标记found为True。
  2. 更新原CSV文件:读取Cars.csv所有行,过滤掉目标行后重新写入原文件,实现删除效果。
  3. 合并追加数据:将收集到的销售数据(售价、销售日期、销售人员)追加到目标行末尾。
  4. 写入目标CSV:将合并后的完整行写入SoldCars.csv,文件不存在时自动创建。

完整实现代码

import csv
import os

def process_sold_car():
    found = False
    target_row = None
    reg = ""
    
    # 1. 搜索目标车辆行
    while not found:
        reg = input("\nEnter the registration number of the car sold\n")
        with open("Cars.csv", "r", newline="") as sale_file:
            reader = csv.reader(sale_file)
            for row in reader:
                if row[2] == reg:
                    found = True
                    target_row = row.copy()
                    break
        if not found:
            print("\nRegistration not found, please try again\n")
    
    # 2. 收集追加的销售数据
    seller_name = input("\nPlease enter your name\n")
    sale_price = int(input("\nHow much did this car sell for?\n"))
    sale_date = input("\nWhat date was the car sold?\n")
    # 按测试数据要求追加字段,如需佣金可继续扩展
    additional_data = [sale_price, sale_date, seller_name]
    # 若需添加佣金数据:additional_data.extend([200, 300])
    
    # 3. 合并原行与追加数据
    updated_row = target_row + additional_data
    
    # 4. 更新原Cars.csv - 删除目标行
    with open("Cars.csv", "r", newline="") as infile, open("temp_cars.csv", "w", newline="") as outfile:
        reader = csv.reader(infile)
        writer = csv.writer(outfile)
        for row in reader:
            if row[2] != reg:
                writer.writerow(row)
    # 替换原文件(Windows环境下需先删除原文件)
    os.remove("Cars.csv")
    os.rename("temp_cars.csv", "Cars.csv")
    
    # 5. 写入SoldCars.csv
    with open("SoldCars.csv", "a", newline="") as sold_file:
        writer = csv.writer(sold_file)
        writer.writerow(updated_row)
    
    print("\nCar record has been moved to SoldCars.csv successfully!")

# 执行处理流程
process_sold_car()

测试验证

以测试数据为例:

  • Cars.csv中原行:BMW,Silver,ABC123,20000,10 4 23,Adam
  • 追加销售数据后合并行:BMW,Silver,ABC123,20000,10 4 23,Adam,30000,20 4 23,Daisy,200,300
  • 执行后,Cars.csv中该行被删除,SoldCars.csv中新增上述合并后的行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 06:07:20