【问题标题】:Python saving to file with limitationsPython保存到文件有限制
【发布时间】:2015-02-09 12:08:07
【问题描述】:

我的代码设置为仅允许将特定用户的 3 个分数保存在文本文件中。但我正在努力完成这项工作。 pname 是人名的变量,他们正确的数量存储在变量正确的下面。我还试图添加他们使用变量 etime 所花费的时间。我有基础,但无法修复错误或使其工作,因为我试图将其从另一个答案调整为另一个问题。 谢谢你。

                SCORE_FILENAME  = "Class1.txt"
                MAX_SCORES = 3

                try: scoresFile = open(SCORE_FILENAME, "r+")
                except IOError: scoresFile = open(SCORE_FILENAME, "w+") # File not exists
                actualScoresTable = []
                for line in scoresFile:
                    tmp = line.strip().replace("\n","").split(",")
                    actualScoresTable.append({
                                            "name": tmp[0],
                                            "scores": tmp[1:],
                                            })
                scoresFile.close()

                new = True
                for index, record in enumerate( actualScoresTable ):
                    if record["name"] == pname:
                        actualScoresTable[index]["scores"].append(correct)
                        if len(record["scores"]) > MAX_SCORES:
                            actualScoresTable[index]["scores"].pop(0) # OR del actualScoresTable[index]["scores"][0]
                        new = False
                        break
                if new:
                    actualScoresTable.append({
                                             "name": pname,
                                             "scores": correct,
                                             })

                scoresFile = open(SCORE_FILENAME, "w+") # Truncating file (write all again)
                for record in actualScoresTable:
                    scoresFile.write( "%s,%s\n" % (record["name"], ","(record["scores"])) )
                scoresFile.close()

【问题讨论】:

  • 我认为您的问题会从简化中受益。
  • 确实如此,而且是我班上唯一一个这样做的人。和全国6%的一部分。我在挣扎。甚至我的老师也帮不了我,因为他们对 Python 也不太了解。那么有人可以帮忙吗?我只是想让它保存变量:pname、correct 和 etime(人名、他们正确的数量和花费的时间)所以我希望它看起来像这样:
  • 姓名、分数、所用时间、分数、所用时间、分数、所用时间。它必须只有 3 分,因为这是整个任务的任务 3 的标准。我知道如何正常保存它们,因为我的旧解决方案是这样做的,但不是标准任务 3 要求的。谢谢。
  • 抱歉,之前没有看到您的回复。当您回复某人的评论时,您需要在他们的用户名前使用@ 来提醒他们;您会自动收到警报,因为这是您的问题。请参阅meta.stackoverflow.com/editing-help#comment-formatting 了解更多信息。无论如何,很多 人在这里问过这个问题,因此您可以通过 Google(或您选择的搜索引擎)在 site:http://stackoverflow.com save last three scores text 上进行搜索来获得一些有用的提示

标签: python python-3.x limiting


【解决方案1】:

首先,您在将分数写入文件时遇到了问题:

...
scoresFile.write( "%s,%s\n" % (record["name"], ","(record["scores"])) )
...

由于","(record["scores]),此行引发了 TypeError。为了解决这个问题,只需删除",",这似乎是一个错字。

之后,您在覆盖当前分数时出现语义错误。一方面,您将已输入的分数读取为字符串:

...
tmp = line.strip().replace("\n","").split(",")
actualScoresTable.append({
                        "name": tmp[0],
                        "scores": tmp[1:],
                        })
...

此外,不是以name,score1,score2,... 格式写入分数,而是将其写入name,[score1, score2],因为您正在编写原始列表对象,也在以下行中:

...
scoresFile.write( "%s,%s\n" % (record["name"], ","(record["scores"])) )
...


接下来,要解决导致程序错误输出分数的问题,您必须更改一些内容。一方面,您必须确保在从文件中获取分数时,将它们更改为整数。

...
for line in scoresFile:
    tmp = line.strip().replace("\n","").split(",")

    # This block changes all of the scores in `tmp` to int's instead of str's
    for index, score in enumerate(tmp[1:]):
        tmp[1+index] = int(score) 

    actualScoresTable.append({
                            "name": tmp[0],
                            "scores": tmp[1:],
                            })
...

之后,您还必须确保在创建新条目时,即使只有一个分数也将其存储在列表中:

...
if new:
    actualScoresTable.append({
                             "name": pname,
                             "scores": [correct], # This makes sure it's in a list
                             })
...

最后,为了确保程序以正确的格式输出分数,您必须将它们转换为字符串并在它们之间放置逗号:

...
for record in actualScoresTable:

    for index, score in enumerate(record["scores"]):
        record["scores"][index] = str(score)

    # Run up `help(str.join)` for more information
    scoresFile.write( "%s,%s\n" % (record["name"], ",".join(record["scores"])) )
...


这应该这样做。如果有什么问题,请告诉我!

【讨论】:

  • 嘿,感谢您的帮助,一切正常,但我无法将我的分数输出和排序等。有什么地方可以直接与您联系吗?谢谢你:)
猜你喜欢
  • 2011-01-15
  • 1970-01-01
  • 2012-03-21
  • 2018-02-24
  • 2015-11-24
  • 1970-01-01
  • 2019-04-09
  • 2013-10-30
  • 1970-01-01
相关资源
最近更新 更多