在python中将输出写入文件

时间:2018-04-14 09:10:07

标签: python python-3.x text-files

我需要从文本文件中读取输入并创建一个包含输出的新文本文件。目前我的代码读取正常,但它只写了最后一行数据,而不是通过所有行。有人可以帮我解决这个问题吗?

def generate_daily_totals(input_filename, output_filename):
  """Returns date followed by the sum of values"""
  infile = open(input_filename)

for line in infile:
    content = line.split(",")
    date = content[0]
    total = 0
    for value in content[1:]:
        total = total + float(value)
    rounded_total = "{:.2f}".format(total)
    summary = date + " " + "=" + " "  + rounded_total
  outfile = open(output_filename, "w")
  outfile.write(summary)    

generate_daily_totals('data60.txt', 'totals60.txt')
checker = open('totals60.txt')
print(checker.read())
checker.close() 

输入

2006-04-10,836.2,563.263
2006-04-10,462.06,1694.3,666.0
2006-04-10,1318.19,1485.62
2006-04-10,49.714,304.0,1269.0
2006-04-10,1360.0,1731.0,28.6
2006-04-10,998.879,890.264,367.0
2006-04-10,757.4,1501.05,861.6
2006-04-10,1218.0,270.0

我得到的输出是

2006-04-10 = 1488.00

但正确的应该是

2006-04-10 = 1399.46
2006-04-10 = 2822.36
2006-04-10 = 2803.81
2006-04-10 = 1622.71
2006-04-10 = 3119.60
2006-04-10 = 2256.14
2006-04-10 = 3120.05
2006-04-10 = 1488.00

3 个答案:

答案 0 :(得分:1)

您的代码在循环内重新打开输出文件。每次执行此操作时,它都会覆盖前一次循环所执行的操作。

outfile = open(output_filename, "w")
outfile.write(summary)  

在开始循环输入之前打开输出文件。

with open(output_filename, "w") as outfile:
  for line in infile:
    content = line.split(",")
    date = content[0]
    total = 0
    for value in content[1:]:
        total = total + float(value)
    rounded_total = "{:.2f}".format(total)
    summary = date + " " + "=" + " "  + rounded_total + "\n"
    outfile.write(summary)   

答案 1 :(得分:0)

您的代码存在以下问题:

outfile = open(output_filename, "w")

通过将文件作为写入文件打开,可以覆盖文件中的其他所有内容。相反,你应该使用append:

outfile = open(output_filename, "a")

答案 2 :(得分:0)

您需要以append模式打开输出文件。

def generate_daily_totals(input_filename, output_filename):
    """Returns date followed by the sum of values"""
    infile = open(input_filename)

    for line in infile:        
        content = line.split(",")
        date = content[0]
        total = sum(map(float, content[1:])) # No need for the inner loop
        rounded_total = "{:.2f}".format(total)
        summary = date + " " + "=" + " "  + rounded_total        
        outfile = open(output_filename, "a")
        outfile.write(summary + '\n')

generate_daily_totals('data60.txt', 'totals60.txt')

写入文件的输出:

2006-04-10 = 1399.46
2006-04-10 = 2822.36
2006-04-10 = 2803.81
2006-04-10 = 1622.71
2006-04-10 = 3119.60
2006-04-10 = 2256.14
2006-04-10 = 3120.05
2006-04-10 = 1488.00