为何字典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
相关产品推荐
相关产品推荐

