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

为何字典l1中追加的数据未写入output.csv文件?

问题排查与修复方案

核心问题

你创建的DataFrame df 是基于初始空字典l1生成的独立对象,后续往l1里追加数据时,df不会自动同步更新。最后写入CSV的还是最初的空DataFrame,所以看不到新增内容。


修复方案1:每次追加数据后同步更新DataFrame

每次往字典l1加完数据后,重新生成DataFrame,确保df包含最新数据:

import pandas as pd

l1 = {"name": [], "order no": [], "price": []}
df = pd.DataFrame(l1)
while (True):
  exit = input("enter exit to exit: ")
  name = input("enter your name: ")
  order_no = int(input("enter your order no: "))
  price = int(input("enter your price: "))
  printing = input("type print to print data: ")
  if (exit == "exit" or printing == "print"):
    df.to_csv("output.csv", index=False)  # 加index=False避免生成默认行号
    break
  else:
    l1["name"].append(name)
    l1["order no"].append(order_no)
    l1["price"].append(price)
    df = pd.DataFrame(l1)  # 重新生成df,同步最新数据
    print(l1)

修复方案2:直接往DataFrame追加行(更高效)

跳过字典维护,直接构造单行数据追加到df中,避免重复生成DataFrame的开销:

import pandas as pd

df = pd.DataFrame(columns=["name", "order no", "price"])
while (True):
  exit = input("enter exit to exit: ")
  name = input("enter your name: ")
  order_no = int(input("enter your order no: "))
  price = int(input("enter your price: "))
  printing = input("type print to print data: ")
  if (exit == "exit" or printing == "print"):
    df.to_csv("output.csv", index=False)
    break
  else:
    # 构造单行数据并追加到df
    new_row = pd.Series({"name": name, "order no": order_no, "price": price})
    df = pd.concat([df, new_row.to_frame().T], ignore_index=True)
    print(df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 23:32:37