如何从每个print
收集多个字符串作为一个函数写入另一个文件?
(如果我的措辞正确的话)
Heres就是我所拥有的:
heart_max,heart_min = find_max_min (wanted_tuples, 0,1)
print ('Heart: {} {:.1f} {} {:.1f}'.format(heart_min[1],heart_min[0],heart_max[1],heart_max[0]))
#
mv_max,mv_min = find_max_min (wanted_tuples, 0,2)
print ('Motor: {} {:.1f} {} {:.1f}'.format(mv_min[1],mv_min[0],mv_max[1],mv_max[0]))
#
birth_max,birth_min = find_max_min (wanted_tuples, 0,3)
print ('Birth: {} {:.1f} {} {:.1f}'.format(birth_min[1],birth_min[0],birth_max[1],birth_max[0]))
#
smoke_max,smoke_min = find_max_min (wanted_tuples, 0,4)
print ('Smoking: {} {:.1f} {} {:.1f}'.format(smoke_min[1],smoke_min[0],smoke_max[1],smoke_max[0]))
#
ob_max,ob_min = find_max_min (wanted_tuples, 0,5)
print ('Obesity: {} {:.1f} {} {:.1f}'.format(ob_min[1],ob_min[0],ob_max[1],ob_max[0]))
outstring = {'Heart:'' {} {:.1f} {} {:.1f}'.format(heart_min[1],heart_min[0],heart_max[1],heart_max[0])},
'Motor: {} {:.1f} {} {:.1f}'.format(mv_min[1],mv_min[0],mv_max[1],mv_max[0])),
'Birth: {} {:.1f} {} {:.1f}'.format(birth_min[1],birth_min[0],birth_max[1],birth_max[0])),
'Smoking: {} {:.1f} {} {:.1f}'.format(smoke_min[1],smoke_min[0],smoke_max[1],smoke_max[0])),
'Obesity: {} {:.1f} {} {:.1f}'.format(ob_min[1],ob_min[0],ob_max[1],ob_max[0]))}
然后将结果写入此文件
f_write = open('best_and_worst.txt', 'w') #creates the file
try:
f_write.writelines(outstring)
finally:
f_write.close()
我将这样的字符串格式化,这样我可以在运行时使输出看起来像这样:
Min Max
Heart: Minnesota 1.8 Missouri 26.4
Motor: Washington 2.8 Colorado 34.6
Birth: Ohio 4.4 New York 43.2
Smoking: Utah 6.1 Ohio 44.3
Obesity: Michigan 19.1 Mississippi 37.3
我整个长程序运行良好而没有错误。由于某种原因,我在如何做到这一点上画了一个空白。任何帮助或指导表示赞赏。
答案 0 :(得分:2)
不要使用print()
,只需将字符串存储在列表中并将字符串写入文件:
output = []
heart_max,heart_min = find_max_min (wanted_tuples, 0,1)
output.append('Heart: {} {:.1f} {} {:.1f}'.format(heart_min[1],heart_min[0],heart_max[1],heart_max[0]))
mv_max,mv_min = find_max_min (wanted_tuples, 0,2)
output.append('Motor: {} {:.1f} {} {:.1f}'.format(mv_min[1],mv_min[0],mv_max[1],mv_max[0]))
# etc.
with open('best_and_worst.txt', 'w') as f_write:
f_write.write('\n'.join(output))