2014-12-03 27 views
-3

這是我的程序。除了我需要放置投球手名稱,分數和標題(平均,完美,低於平均水平,高於平均水平)的部分以外,一切都可以正常工作。如何確保所有部件進入outfile?非常感謝!從程序中寫入輸出文件python

***好的,所以我得到了正確的文件輸出除了沒有添加標題。我需要的輸出是這個樣子:

Jane 160 Below Average Hector 300 PERFECT! Mary 195 Above Average Sam 210 Above Average David 102 Below Average

scores = {} 



def bowl_info(filename): 
    infile = open("bowlingscores.txt", "r") 
    total = 0 
    for line in infile:  
     if line.strip().isdigit(): 
      score = int(line)  
      scores[name] = score 


     else: 
      name = line.strip() 
    return scores 

def titles(): 
    for name, score in scores.items():  
     if score == 300: 
      print name , score, "PERFECT!" 
     elif score < average: 
      print name , score, "Below Average" 
     elif score > average: 
      print name , score, "Above Average" 
     else: 
      print name , score, "Average" 

bowl_info("bowlingscores.txt") 
numbowlers = len(scores) 
total = sum(scores.values()) 
average = total/numbowlers 
titles() 

for items in scores.items():  
    outfile = open("bowlingaverages.txt", "w") 
+0

具體什麼是你遇到的麻煩?您是否嘗試過搜索「在Python中寫入文件」? – 2014-12-03 01:21:39

+0

我不確定如何確保名稱,分數和標題(如函數中定義的)在輸出文件中。我想我擁有除標題以外的一切。 – Holly 2014-12-03 02:40:57

回答

2

下面是如何寫入一個文件在你的情況蟒蛇

file = open("newfile.txt", "w") 

file.write("This is a test\n") 

file.write("And here is another line\n") 

file.close() 

你忘了寫()和關閉()

+0

非常感謝! – Holly 2014-12-03 02:50:53

+0

當然...我只需點擊複選標記,對不對? – Holly 2014-12-04 21:03:21

1

你不實際寫入文件:

with open("bowlingaverages.txt", "w") as outfile: 
    for name, score in scores.items(): 
     outfile.write(name + ":" + str(score)) 

作爲一個側面說明,你應該總是使用with語法時打開文件,see here。這確保文件無論如何都能正確關閉。這是你沒有做的事情。你的bowlinfo()函數實際上並沒有使用它的參數filename

最後一件事,如果您使用python 2.7,那麼您應該使用scores.iteritems()而不是scores.items()。如果你使用python 3,那很好。見this question

編輯

你沒有得到的標題在outfile中,因爲你只是將它們打印在您titles()方法。您需要將標題保存到某個位置,以便將它們寫入文件。試試這個:

titles = {} 
def titles(): 
    for name, score in scores.iteritems(): 
     if score === 300: 
      titles[name] = "PERFECT!" 
     elif score < average: 
      titles[name] = "Below average" 
     elif score > average: 
      titles[name] = "Above average" 
     else: 
      titles[name] = "Average" 

現在你已經保存了每個玩家的標題,你可以改變上面我的​​代碼:

with open("bowlingaverages.txt", "w") as outfile: 
    for name, score in scores.iteritems(): 
     s = name + ":" + str(score) + " " + titles[name] + "\n" 
     outfile.write(s) 
     # if you still want it to print to the screen as well, you can add this line 
     print s 

您可以輕鬆更改的打印是什麼格式/寫入文件通過更改s的值。

+1

我得到這個錯誤:TypeError:期望一個字符緩衝區對象 – Holly 2014-12-03 01:26:18

+0

請看我的編輯。 – 2014-12-03 01:30:46

+0

非常感謝!關於bowl_info的參數...我應該將它留空或定義文件名? – Holly 2014-12-03 02:39:45