0

Python error : Python ValueError: I/O operation on closed file

I am trying code

import random

with open("GoneGirlSW.txt", "r") as f,open('trainData.txt','w') as   trainFile,open('testData.txt','w') as testFile:
    data = f.read().split('\n')
    random.shuffle(data)
    train_data = data[:50]
    test_data = data[50:]

    trainFile.write(str(train_data))
    testFile.write(str(test_data))

But it is giving error

Traceback (most recent call last):
  File "trainTest.py", line 9, in <module>
    trainFile.write(str(train_data))
ValueError: I/O operation on closed file.
3
  • Looks like " trainFile.write(str(train_data))" is out side "with". Commented Apr 10, 2017 at 6:11
  • 1
    "with" automatically closes the file once it is outside it's scope. Commented Apr 10, 2017 at 6:12
  • Perhpas you have edited the code in response to my answer (or somebody else did)? I doubt the version you currently list will actually demonstrate the problem you report ... Commented Apr 10, 2017 at 7:25

3 Answers 3

2

A file is closed automatically when a with/as statement is completed. In your case, the with/as statement is completed immediately due to a lack of indentation. The code should read:

 import random

with open("GoneGirlSW.txt", "r") as f, open('trainData.txt','w') as trainFile, open('testData.txt','w') as testFile:
  data = f.read().split('\n')
  random.shuffle(data)
  train_data = data[:50]
  test_data = data[50:]

  trainFile.write(str(train_data))
  testFile.write(str(test_data))
Sign up to request clarification or add additional context in comments.

Comments

1

Difficult to know, since your code doesn't appear correctly indented. I am assuming this is because you aren't yet familiar with question editing.

The purpose of the with statement is to let you execute code in a known context. In the case of opening files, it guarantees that the file is closed at the end of the indented suite. So I am guessing that you haven't indented the last two statements so they are part of the code covered by the with.

Comments

0

Lines of code after with statement should be indented

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.