将数据保存到文件时的Python TypeError

时间:2015-02-23 11:46:38

标签: python string format typeerror

我正在尝试将选择用户数据保存到文件的代码区域。我使用的代码可以保存用户最好的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.")

2 个答案:

答案 0 :(得分:0)

您的格式字符串包含两个值,但您传入三个

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

您似乎正在重塑CSV写作;改为使用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)

答案 1 :(得分:0)

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

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

字符串&#34;,&#34; &#34; ETIME&#34;成为一个字符串&#34;,etime&#34;这是第三个参数,它应该在连接括号内吗?