我正在努力工作的代码领域,保存选定的用户数据到文件。我使用的代码保存了一个用户最好的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.")
我在那里只看到两个占位符
%s
标记,后面的列表中有三个项目。也许这样的格式更明显:字符串“,”etime“变成了一个字符串”,etime“是第三个参数,它应该在连接括号内吗?你知道吗
您的格式字符串中有两个值,但您要传入三个值:
您似乎正在重新设计CSV编写;请改用^{} module :
相关问题 更多 >
编程相关推荐