2013-03-11 58 views
0

如何從每個print收集多個字符串作爲一個函數來寫入另一個文件? (如果我的措辭這一權利)如何將五個字符串寫入一個文件

繼承人是我:

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 

我整個長程序運行fi ne沒有錯誤。只是由於某種原因,我在如何做到這一點上留下了空白。任何幫助或指導表示讚賞。

回答

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)) 
+0

其實我本來以爲,這(無後處理,而只是緩衝輸出)這正是問題所在,這是StringIO模塊設計要解決的問題,至少有機會需要更少的內存開銷 - 不是嗎? – guidot 2013-03-11 22:01:20

+0

@guidot:你也可以直接寫入文件。在這種情況下,StringIO實例不會保存在內存中。 – 2013-03-11 22:02:35

+0

謝謝你的指導。 – 2013-03-11 22:29:20

相關問題