【问题标题】:Python TypeError when saving data to file将数据保存到文件时出现 Python TypeError
【发布时间】:2015-04-24 17:38:51
【问题描述】:

我正在尝试处理将选定用户数据保存到文件的代码区域。我正在使用一个代码来保存用户的最佳 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.")

【问题讨论】:

  • scoresFile.write( "%s,%s\n" % (record["name"], ",".join(record["scores"]), "," "etime") )更改为scoresFile.write( "%s,%s,etime\n" % (record["name"], ",".join(record["scores"])) )
  • 尝试在您的 Python 提示符中简单地使用格式化的字符串,直到正确为止,即 %s,%s\n" % (record["name"], ",".join(record["scores"]), "," "etime"),因为其他人指出您没有足够的占位符用于您的参数。事实上,现在是您研究新格式语法的好时机,将函数附加到保存参数的字符串。这样,参数数量与其占位符之间的关系就变得更加清晰。像这样,{name:s}, {scores:d}, etime".format(name=record["name"],scores=record["scores"])

标签: python string format typeerror


【解决方案1】:

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

("%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)

【讨论】:

  • 哦,对不起,我不应该包含最后一点,那是我之前的测试,我正在尝试将它写为 txt 文件来改进它。我无法将变量“etime”保存为他们完成任务所花费的时间。我必须将其保存为 ["etime"] 吗?另外,当我查看分数时,如何使用这些数据将自己从高到低排序?
  • @PythonBeginner:我假设您想在该列中附加文字文本etime; CSV 示例生成一个列表,其中包含 record['name'] 的单独条目以及 record['scores'] 的每个元素,后跟该字符串。如果您需要排序数据,请使用sorted() 生成排序列表。
  • 我已经用占位符问题修复了当前的问题,但现在我已经尝试过了。 scoreFile.write("%s,%s,%s\n" % (record["name"], ",".join(record["scores"], "," , ["etime"])))现在我得到错误: Traceback(最近一次调用最后一次):文件“C:\Users\sfawcett\Desktop\MainCode”,第 161 行,在 tmp[1+index] = int(score) ValueError: invalid以 10 为底的 int() 的文字:'etime'。这是什么意思? @MartijnPieters
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 2016-02-01
    • 2021-04-29
    • 2018-09-11
    相关资源
    最近更新 更多