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

如何用带变量的Python print语句写入CSV文件

Python新手问题:将终端输出的计算结果写入CSV文件

我是Python新手,有一个明确的需求:需要将终端输出的含变量的计算结果同时写入CSV文件。目前终端已能正常输出正确结果,但无法将这些带变量的输出内容(如显示具体数值的盈利/亏损统计语句)写入CSV,而非带变量占位符的格式。我仅具备将完整列表写入CSV的经验,附上相关代码如下:

import os 
import csv

date = []
profloss = []
changes = []
total = 0
totalChange = 0 
mo2mo = {}


budget_csv = os.path.join(xxxxxx)

with open(budget_csv) as csvfile:
    csvreader = csv.reader(csvfile, delimiter=",")

#splitting the two columns into seperate lists
    for row in csvreader:
        date.append(row[0])
        profloss.append(row[1])
    
#removing header rows
    date.pop(0)
    profloss.pop(0)

#printing how many months are in the data set
    dataLen = len(date)
    countMonths = "This data set has " + str(len(date)) + " months." 
    
#calculating total profit/loss
    for i in range(0, len(profloss)):
        profloss[i] = int(profloss[i])
        total = total + (profloss[i])
    print(f'The total profit/loss for this period is: ${total}')

#calculating the difference between months and adding it to a list
    for i in range(0, len(profloss)-1):
        difference = (profloss[i+1]) - (profloss[i])
        changes.append(difference)

#removing the first element in date to make a dictionary for dates: changes
    date.pop(0)
    
#creating a dictionary of months as keys and change as values, starting with the second month
    mo2mo = {date[i]: changes[i] for i in range(len(date))}
   
#calculating the average change from one month to the next
    
    for i in range(0, len(changes)):
        totalChange = totalChange + changes[i] 
    avChange = totalChange/len(changes)
    print(f'The average change from month to month for this dataset is: {round((avChange),2)}')

#getting the month with the maximum increase
    keyMax = max(mo2mo, key= lambda x: mo2mo[x])

    for key,value in mo2mo.items():
        if key == keyMax:
            print(f'The month with the greatest increase was: {key} ${value}')
    

#getting the month with the maximum decrease
    keyMin = min(mo2mo, key= lambda x: mo2mo[x])
    for key, value in mo2mo.items():
        if key == keyMin:
            print(f'The maximum decrease in profits was: {key} ${value}')
    

outputCSV = ("countMonths",)
output_path = os.path.join("..", "output", "PyBankAnswers.csv")
#writing outcomes to csv file
with open(output_file,"w") as datafile:
    writer = csv.writer(datafile)
    for row in writer.writerow()

不需要手动逐行复制终端语句,你可以把所有统计结果先收集到一个结构化的列表中,这样既能批量打印到终端,又能直接写入CSV,避免重复代码。具体修改方案如下:

  • 收集所有统计结果:把每个需要输出的统计项和对应结果整理成二维列表,包含表头和具体数据:
# 在计算完所有结果后,收集数据
results = [
    ["统计项", "结果"],
    ["数据集中的月份总数", f"{len(date)} 个月"],
    ["该时间段总盈利/亏损", f"${total}"],
    ["月均变化", round(avChange, 2)],
    ["利润最大增长月份", f"{keyMax} ${mo2mo[keyMax]}"],
    ["利润最大下降月份", f"{keyMin} ${mo2mo[keyMin]}"]
]
  • 批量打印结果:循环遍历列表,输出到终端:
# 打印所有结果
for row in results[1:]:  # 跳过表头行
    print(f"{row[0]}: {row[1]}")
  • 写入CSV文件:使用writerows()方法一次性写入整个结果列表,同时修正你原代码中的语法错误(比如未定义output_file、writer.writerow()语法错误):
output_path = os.path.join("..", "output", "PyBankAnswers.csv")
# 写入CSV文件
with open(output_path, "w", newline="") as datafile:
    writer = csv.writer(datafile)
    writer.writerows(results)
  • 替换原代码的输出逻辑:把你原来分散的print()语句和错误的CSV写入代码,替换成上面的收集、打印、写入逻辑即可。

这样做的好处是只需要维护一个results列表,就能同时完成终端输出和CSV写入,不需要重复编写相同的格式化语句,也避免了手动复制的麻烦。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:10:37