2014-12-03 29 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