error when writing to a text file in python [I/O operation on closed file]

时间:2015-10-06 08:33:12

标签: python file text save file-writing

I wanted to make a file in python and i came across a error. i have no idea why it comes up with this, i did look online but couldn't find any solutions to my problem. and i have imported random and i do have a list for enc1

f = open("Skins.txt",'w')
for r in range(1,1201):
   f.write(str(r))
   f.write(",")
   f.write(random.choice(enc1))
   f.write("\n")
   f.close()

The error:

    f.write(str(r))
    ValueError: I/O operation on closed file.

2 个答案:

答案 0 :(得分:3)

You're trying to close the file at end of each iteration. Move close operation out of loop block.

f = open("Skins.txt",'w')
for r in range(1,1201):
   f.write(str(r))
   f.write(",")
   f.write(random.choice(enc1))
   f.write("\n")
f.close()

Or use with to open your file once outside the loop and use writelines to write the data:

with open("Skins.txt",'w') as f:
     f.writelines("{},{}\n".format(r, random.choice(enc1)) for r in range(1,1201))

答案 1 :(得分:1)

You are closing the file inside the loop, hence after the first iteration the file is closed, and hence trying to write to it fails with the error you are getting.

I would suggest using with statement to open the file (so that it automatically handles closing the file for you), so that this kind of issues does not occur. Also, you do not need all those different f.write() statements, you cna use str.format() and do the same in a single .write() .

Example -

with open("Skins.txt",'w') as f:
    for r in range(1,1201):
       f.write("{},{}\n".format(r, random.choice(enc1)))