将数据保存到fi时出现Python TypeError

2024-04-26 19:09:58 发布

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

我正在努力工作的代码领域,保存选定的用户数据到文件。我使用的代码保存了一个用户最好的3分,或者至少我认为是这样。但它目前会出现以下错误:

Traceback (most recent call last):
  File "C:\Users\sfawcett\Desktop\MainCode", line 189, in <module>
    scoresFile.write( "%s,%s\n" % (record["name"], ",".join(record["scores"]), "," "etime") )
TypeError: not all arguments converted during string formatting

代码:

if pclass == 1:
    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(",")

        # 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:],
                                })
    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], # This makes sure it's in a list
                                 })

    scoresFile = open(SCORE_FILENAME, "w+") # Truncating file (write all again)
    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"]), "," "etime") )

    scoresFile.close()
elif pclass == 2:
    inFile = open("bscores.csv", 'a')
    inFile.write("\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1)))
    inFile.close()
    inFile = open("bscores.csv", 'r')
    print(inFile.read())
elif pclass == 3:
    inFile = open("cscores.csv", 'a')
    inFile.write("\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1)))
    inFile.close()
    inFile = open("cscores.csv", 'r')
    print(inFile.read(sorted(reader, key=lambda row: int(row[0]))))
else:
    print("Sorry we can not save your data as the class you entered is 1, 2 or 3.")

Tags: nameinforindexifopenrecordtmp
2条回答

我在那里只看到两个占位符%s标记,后面的列表中有三个项目。也许这样的格式更明显:

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

字符串“,”etime“变成了一个字符串”,etime“是第三个参数,它应该在连接括号内吗?你知道吗

您的格式字符串中有两个值,但您要传入三个值:

("%s,%s\n" %
# 1  2
 (record["name"], ",".join(record["scores"]), "," "etime"))
#     1                     2                    3

您似乎正在重新设计CSV编写;请改用^{} module

with open("cscores.csv", 'ab') as csvfile:
    writer = csv.writer(csvfile)
    # build one list
    row = [record["name"]] + record["scores"] + ['etime']
    writer.writerow(row)

相关问题 更多 >