【发布时间】: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