当我运行mu代码时,它说:
for score in scoresFile: ValueError:关闭文件的I / O操作。
我尝试过很多东西,但不会改变结果。我的代码如下所示:
SCORE_FILENAME = "Class1.txt"
MAX_SCORES = 3
try: scoresFile = open('Class1.txt', "r+")
except IOError: scoresFile = open('Class1.txt', "w+") # File not exists
actualScoresTable = []
for line in scoresFile:
tmp = line.strip().replace("\n","").split(",")
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],
})
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)
scoresFile.write( "%s,%s\n" % (record["name"],(record["scores"])) )
scoresFile.close()
有人可以帮我解决这个问题吗。
答案 0 :(得分:0)
将scoresFile.close()
移出for循环。你在阅读完第一行后就关闭了它。
答案 1 :(得分:0)
问题看起来是第一个for循环中的scoresFile.close()
行。如果文件不止一行,那么在您尝试访问第二行时它将被关闭。我认为如果你将这条线移到循环之外,这个错误就会消失。