【问题标题】:Writing and Reading to/from a file in python在python中写入和读取文件
【发布时间】:2012-11-12 16:38:08
【问题描述】:

如果对我的家庭作业有任何帮助,我将不胜感激 - 这是一个简单的课程程序,用于检查文件,如果存在,它会读取文件,并将数据加载到程序中,这样您就可以列出分数,并添加更多。它应该只保留前 5 名的分数。

然后,当您关闭程序(通过选择选项 0)时,它应该将前 5 个分数写入scores.txt 文件。我想我让它正常工作,我只是无法让程序正确读取和填充scores 文件。

到目前为止,这是我的代码:

scores = []

#Check to see if the file exists
try:
    file = open("scores.txt")
    for i in range(0, 5):
        name = file.readline()
        score = file.readline()
        entry = (score, name)
        scores.append(entry)
        scores.sort()
        scores.reverse()
        scores = scores[:5]
    file.close()
except IOError:
    print "Sorry could not open file, please check path."


choice = None
while choice != "0":

    print    """
    High Scores 2.0

    0 - Quit
    1 - List Scores
    2 - Add a Score
    """


    choice = raw_input("Choice: ")
    print ""

    # exit
    if choice == "0":
        print "Good-bye."
        file = open("scores.txt", "w+")
        #I kinda sorta get this now... kinda...
        for entry in scores:
            score, name = entry
            file.write(name)
            file.write('\n')
            file.write(str(score))
            file.write('\n')
        file.close()

    # display high-score table
    elif choice == "1":
        print "High Scores\n" 
        print "NAME\tSCORE" 
        for entry in scores:
            score, name = entry    
            print name, "\t", score

    # add a score
    elif choice == "2":
        name = raw_input("What is the player's name?: ")
        score = int(raw_input("What score did the player get?: "))
        entry = (score, name)
        scores.append(entry)
        scores.sort()
        scores.reverse()
        scores = scores[:5]     # keep only top 5 scores

    # some unknown choice
    else:
        print "Sorry, but", choice, "isn't a valid choice." 

raw_input("\n\nPress the enter key to exit.")

【问题讨论】:

  • 我已经稍微重新格式化了您的帖子 - 我也会暂时忽略您的编辑 - 一次一件事......
  • 谢谢。我会记住的。
  • 如果您将文件写成 CSV 格式而不是每个字段放在不同的行上会容易得多。
  • 查看:docs.python.org/2/library/csv.html - 你确定你使用的是 2.3 吗?这是一个非常过时的 Python 版本(实际上是 2003 年)
  • @JoshI 哇——我开始怀疑其中一些课程的质量——我在 SO 上看到的越多——我就越气馁:(

标签: python python-2.3


【解决方案1】:

您应该尝试将文件写入Comma-Separated-Value (CSV)。虽然该术语使用“逗号”一词,但该格式实际上仅表示任何类型的一致字段分隔符,每条记录位于一行。

Python 有一个csv module 来帮助读写这种格式。但我将忽略这一点,并出于家庭作业的目的手动完成。

假设你有一个这样的文件:

Bob,100
Jane,500
Jerry,10
Bill,5
James,5000
Sara,250

我在这里使用逗号。

f = open("scores.txt", "r")
scores = []
for line in f:
    line = line.strip()
    if not line:
        continue
    name, score = line.strip().split(",")
    scores.append((name.strip(), int(score.strip())))

print scores
"""
[('Bob', 100),
 ('Jane', 500),
 ('Jerry', 10),
 ('Bill', 5),
 ('James', 5000),
 ('Sara', 250)]
"""

您不必在每次阅读和追加时都对列表进行排序。你可以在最后做一次:

scores.sort(reverse=True, key=lambda item: item[1])
top5 = scores[:5]

我知道lambda 对您来说可能是新的。它是一个匿名函数。我们在这里使用它来告诉排序函数在哪里可以找到比较的键。在这种情况下,我们说对于分数列表中的每个项目,使用分数字段(索引 1)进行比较。

【讨论】:

  • 我不得不稍微修改一下,但它奏效了。主要是我只需要将scores.append(name, score) 切换为scores.append(score,name)。它是倒着读的,我很困惑。哈。不过非常感谢。
  • 哦,好的。好吧,如果您按该顺序存储它们,那么您就不需要排序中的键 lambda。它只会使用第一个索引
猜你喜欢
  • 1970-01-01
  • 2022-01-23
  • 2021-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多