简体   繁体   English

如何使用带有变量的打印语句用 Python 编写 CSV 文件

[英]How to write CSV files with Python using print statements with variables in them

I'm a noob here and I have pretty straight forward question with writing CSV output files with Python.我在这里是个菜鸟,我有一个非常直接的问题,就是用 Python 编写 CSV 输出文件。 I've been googling this for a while and I can't find an answer to my q.我已经用谷歌搜索了一段时间,但找不到我的问题的答案。 I have a bunch of tasks which have to output answers to the terminal as well as write the answers to a CSV output file.我有一堆任务必须将答案输出到终端并将答案写入 CSV 输出文件。 I've got all the correct answers in the terminal but I can't figure out how to write them to a CSV file.我在终端中得到了所有正确答案,但我不知道如何将它们写入 CSV 文件。 My print statements contain variables, and I need the value of the variable printed.我的打印语句包含变量,我需要打印变量的值。 IE "The total profit/loss for this period is: $22564198" should be printed to the CSV not the print statement format which is: 'The total profit/loss for this period is: ${total}' IE“本期总利润/亏损为:$22564198”应该打印到 CSV 而不是打印报表格式,即:'本期总利润/亏损为:${total}'

I'm copying my code below.我正在下面复制我的代码。

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()

I've only got experience printing whole lists to csv files and not actual statements of text.我只有将整个列表打印到 csv 文件的经验,而不是实际的文本语句。 I've tried to find how to do this but I'm not having luck.我试图找到如何做到这一点,但我没有运气。 There's got to be a way without me just writing out the sentence I want printed by hand and having the CSV writer print that statement?有没有办法不用我手写我想打印的句子并让 CSV 编写器打印该语句? OR do I just have to copy the sentence from the terminal and then print those statements row by row?或者我是否只需要从终端复制句子然后逐行打印这些语句?

The print() function accepts a file option to specify that the output should be written to an open file stream. print()函数接受file选项以指定输出应写入打开的文件流。 So you can make all your print() statements twice, once to the terminal and then to the file.因此,您可以将所有print()语句制作两次,一次到终端,然后到文件。 To avoid all this duplication, you can put that into a function.为避免所有这些重复,您可以将其放入一个函数中。 Then call that instead of print() everywhere.然后到处调用它而不是print()

import os 
import csv

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

def print_to_terminal_and_file(f, *args, **kwargs):
    print(*args, **kwargs)
    print(*args, file=f, **kwargs)

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(int(row[1]))
    
#removing header rows
date.pop(0)
profloss.pop(0)

output_path = os.path.join("..", "output", "PyBankAnswers.txt")
#writing outcomes to text file
with open(output_file,"w") as datafile:

    #printing how many months are in the data set
    print_to_terminal_and_file(datafile, f"This data set has {len(date)} months.")

    #calculating total profit/loss
    total = sum(profloss)
    print_to_terminal_and_file(datafile, 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_to_terminal_and_file(datafile, 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_to_terminal_and_file(datafile, 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_to_terminal_and_file(datafile, f'The maximum decrease in profits was: {key} ${value}')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM