-2

When i run mu code it says :

for line in scoresFile: ValueError: I/O operation on closed file.

I have tried many things but it won't change the outcome. My code looks like this:

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

Can someone help me fix this.

Milan Lad
  • 13
  • 3

2 Answers2

0

Move the scoresFile.close() out of your for loop. You're closing it after reading the first line.

Luke Yeager
  • 1,400
  • 1
  • 17
  • 30
  • tmp[1+index] = int(score) ValueError: invalid literal for int() with base 10: "['2']" – Milan Lad Mar 14 '15 at 15:14
  • Now you get to actually parse the data in your file. I leave that to you, or you can post another question if you can't figure it out. Try to figure stuff out yourself before asking on SO - it's for your own good! – Luke Yeager Mar 14 '15 at 15:18
0

The problem looks to be the scoresFile.close() line within the first for loop. If the file is more than one line, then it will be closed by the time you try to access the second line. I think this error will go away if you move that line outside of the loop.

Noah Halford
  • 293
  • 1
  • 6