Python保存到文件有限制

时间:2015-02-09 12:08:08

标签: python python-3.x limiting

我设置的代码只允许保存在文本文件中的特定用户的3个分数。但我正在努力使这项工作。 pname是人名的变量,他们正确的数量存储在变量right下。我也在尝试添加他们使用变量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()

1 个答案:

答案 0 :(得分:0)

首先,你有一个问题,你写了分数到文件:

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


这应该做到这一点。如果有什么东西不起作用,请告诉我!