如何将输出写入文件,文件名作为第二个参数传递


def generate_daily_totals(input_filename, output_filename):
"""result in the creation of a file blahout.txt containing the two lines"""
with open(input_filename, 'r') as reader, open(output_filename, 'w') as writer: #updated

for line in reader: #updated   
pieces = line.split(',')
date = pieces[0]
rainfall = pieces[1:] #each data in a line 
total_rainfall = 0
for data in rainfall:
pure_data = data.rstrip()
total_rainfall = total_rainfall + float(pure_data)

writer.write(date + "=" + '{:.2f}'.format(total_rainfall) + 'n') #updated
#print(date, "=", '{:.2f}'.format(total_rainfall)) #two decimal point format, 
generate_daily_totals('data60.txt', 'totals60.txt')
checker = open('totals60.txt')
print(checker.read())
checker.close()

通过读取文件,原始程序运行良好,但我需要通过编写文件来转换它。我很困惑,因为写方法只适用于字符串,所以这是否意味着只有打印部分可以用写方法代替?这是我第一次尝试使用write方法。谢谢

编辑:以上代码是根据blhsing指令更新的,这对我们帮助很大!但是仍然没有像for循环那样运行良好,因为某些原因,for循环被跳过了。如有适当建议,不胜感激!

expected output:
2006-04-10 = 1399.46
2006-04-11 = 2822.36
2006-04-12 = 2803.81
2006-04-13 = 1622.71
2006-04-14 = 3119.60
2006-04-15 = 2256.14
2006-04-16 = 3120.05
2006-04-20 = 1488.00

您应该打开用于读取的输入文件和用于写入的输出文件,因此更改:

with open(input_filename, 'w') as writer:
for line in writer: # error not readable

至:

with open(input_filename, 'r') as reader, open(output_filename, 'w') as writer:
for line in reader:

此外,与print函数不同,文件对象的write方法不会自动向输出中添加尾随换行符,因此您必须自己添加。

更改:

writer.write(date + "=" + '{:.2f}'.format(total_rainfall))

至:

writer.write(date + "=" + '{:.2f}'.format(total_rainfall) + 'n')

或者您可以将print与指定为file参数的输出文件对象一起使用:

print(date, "=", '{:.2f}'.format(total_rainfall), file=writer)

相关内容

最新更新