从程序中写出输出文件python

时间:2014-12-03 01:16:16

标签: python

这是我的计划。除了我需要输入投球手的名字,得分和头衔(平均,完美,低于平均水平,高于平均水平)之外,一切都有效。如何确保所有部分都进入outfile?非常感谢!

***好的,所以我得到的文件输出正确,除了没有添加任何标题。我需要输出看起来像这样:

  

Jane 160低于平均水平    Hector 300完美!   Mary 195高于平均水平   山姆210高于平均水平   大卫102低于平均水平

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")

2 个答案:

答案 0 :(得分:2)

以下是如何在python中写入文件

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

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

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

file.close()

在您的情况下,您忘记写()并关闭()

答案 1 :(得分:1)

您实际上并没有写入该文件:

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

作为旁注,打开文件see here时应始终使用with语法。无论如何,这都可以确保文件正确关闭。这是你没有做的事情。此外,您的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的值来轻松更改打印/写入文件的格式。