附加到数据列表写入CSV

2024-06-16 08:33:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写一个程序,记录最后三次考试的尝试(分数)。用户可以在任何时候重新进行测试,因此程序必须找到用户是否存在,并附加用户最新的分数。如果用户不存在,则必须在用户首次尝试的同时记录用户名。我已经设法让程序/函数来记录用户的第一个分数,但是如果用户存在,我很难追加更多的尝试。我也不知道如何阻止列表的增长——它应该只记录最后三次尝试——进一步的尝试应该重写现有的。如果这是错误的,请原谅我的无知-我正在学习。在

我需要输出如下所示:(3次尝试后,列表需要开始重写自身

弗雷德,18,17,16

保罗,15,12,16

代码并没有完全按照我的要求执行,但唯一的错误是当用户已经存在时:分数文件.写入(行+“\n”) 值错误:对关闭的文件执行I/O操作

#add score
def main():
    #ask for name and score
    name = input("Please enter the name you wish to add")
    score = input("Please enter the high score")
    message=""

    #open the highscores line and read in all the lines to a list called ScoresList. Then close the file.
    scoresFile = open("highscores.txt","r")
    ScoresList = scoresFile.readlines()
    scoresFile.close()

    #for each line in the ScoresList list
    for i in range(0, len(ScoresList) ):

        #check to see if the name is in the line
        if name in ScoresList[i]:

            #append the score to the end of the list
            ScoresList[i] = (name + (str(score) + ","))

            #write the scores back to the file. Overwrite with the new list
            scoresFile = open("highscores.txt","w")
            for line in ScoresList:
                scoresFile.write(line + "\n")
                scoresFile.close()

            #no need to continue in the loop so break out.
            #break
            else:
                # message as user does not exist
                message = ""

#if message is still blank then it means that the name was not found. Open the
#file for appending and add the new name and score to the end.
    if message=="":
        message = "New score added."
        scoresFile = open("highscores.txt","a")
        scoresFile.write(name + str(score)+"\n")
        scoresFile.close()


    print(message)

main()

Tags: andtheto用户nameinmessagefor
1条回答
网友
1楼 · 发布于 2024-06-16 08:33:08

一个自我解释的问题解决方案:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# name,score_1,score_2,score_3
# append score to a user
# |_ if user not exists: add user and new score
# |_ an user can't have more than 3 scores


SCORE_FILENAME  = "highscores.txt"
MAX_SCORES = 3

def getName():
    return raw_input("Please enter the name you wish to add: ").strip()
def getScore():
    return raw_input("Please enter the high score: ").strip()
def log(*msg):
    print "\t[LOG] " + " ".join([word for word in msg])


if __name__ == "__main__":

    # Get new name and Score:
    newName = getName()
    newScore = getScore()
    log("NewUser and NewScore = %s,%s" % (newName,newScore))

    # open file and get actual scores:
    log("Opening score file: %s" % SCORE_FILENAME)
    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()
    log("Actual score table: %s" % actualScoresTable)

    # update scores or insert new record:
    new = True
    for index, record in enumerate( actualScoresTable ):
        if record["name"] == newName:
            # The user exists in scores table, check how many scores he has:
            if len(record["scores"]) >= MAX_SCORES: 
                # Max. Scores permitted. What to do here?
                log("Actual user '%s' already have %s scores '%s'. What we have to do now?" % (newName, MAX_SCORES, ",".join(record["scores"])))
            else:
                log("Add score '%s' to '%s' that now have [%s]" % (newScore,newName,",".join(record["scores"])))
                actualScoresTable[index]["scores"].append(newScore)
            new = False
            break
    if new:
        log("User '%s' not exists in actual Scores Table. So append it." % newName)
        actualScoresTable.append({
            "name": newName,
            "scores": [newScore],
        })

    # Save result to file and close it:
    scoresFile = open(SCORE_FILENAME, "w+") # Truncating file (write all again)
    for record in actualScoresTable:
        scoresFile.write( "%s,%s\n" % (record["name"], ",".join(record["scores"])) )
    log("Writing changes to file: %s" % actualScoresTable)
    scoresFile.close()

注意事项:

  1. 为了改进这个解决方案,有许多不同的改进(在打开的文件中使用with操作,如果是记录更新,则直接写入-而不是截断文件…)。我想说得更清楚,因为你的绰号是:“learningpython”;)
  2. 我不知道如果用户已经有了这三个分数(重新开始,从第一次添加删除,从最后一次添加删除(…),那么我没有编写代码。。在

编辑以满足新要求:

^{pr2}$

相关问题 更多 >