Python 如何将输出写入作为第二个参数传递的文件?
通过读取文件,原始程序运行良好,但我必须通过编写文件来转换它。我很困惑,因为write方法只适用于string,所以这是否意味着write方法只能替换print部分?这是我第一次尝试使用write方法。谢谢 编辑:以上代码已根据blhsing指令进行更新,帮助很大!但是仍然没有像for循环那样运行良好,因为某些原因被跳过。适当的建议将不胜感激Python 如何将输出写入作为第二个参数传递的文件?,python,Python,通过读取文件,原始程序运行良好,但我必须通过编写文件来转换它。我很困惑,因为write方法只适用于string,所以这是否意味着write方法只能替换print部分?这是我第一次尝试使用write方法。谢谢 编辑:以上代码已根据blhsing指令进行更新,帮助很大!但是仍然没有像for循环那样运行良好,因为某些原因被跳过。适当的建议将不胜感激 def generate_daily_totals(input_filename, output_filename): """result in
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()
您应该同时打开输入文件进行读取,同时打开输出文件进行写入,因此请更改:
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
致:
此外,与函数print
不同,file对象的write
方法不会自动向输出中添加尾随的换行符,因此您必须自己添加它
更改:
with open(input_filename, 'r') as reader, open(output_filename, 'w') as writer:
for line in reader:
致:
或者您可以使用print
,将输出文件对象指定为file
参数:
writer.write(date + "=" + '{:.2f}'.format(total_rainfall) + '\n')
谢谢@blhsing,我确实遵循了您的指导,但在运行了第行“以open(input_filename,'r')作为读卡器,以open(output_filename,'w')作为写卡器”之后:“程序只是跳到第23行的函数调用,直到最后。我想知道我的原始代码还有其他问题吗?再次感谢,关于此说明,没有进一步的问题!如果它没有做任何事情,听起来好像输入文件是空的。由于我的原始with语句处理,输入文件contect被擦除,这就是循环被跳过的原因。我想我所有的问题都解决了!再次感谢!
writer.write(date + "=" + '{:.2f}'.format(total_rainfall))
writer.write(date + "=" + '{:.2f}'.format(total_rainfall) + '\n')
print(date, "=", '{:.2f}'.format(total_rainfall), file=writer)