5

I am following a tutorial to learn to read and write to a file. I am getting the following error. I do not understand why.

C:\Python27\python.exe "C:/Automation/Python/Write to files/test3.py"
Traceback (most recent call last):
  File "C:/Automation/Python/Write to files/test3.py", line 8, in <module>
    f.read('newfile.txt', 'r')
ValueError: I/O operation on closed file

My code is

f = open("newfile.txt", "w")
f.write("hello world\n")
f.write("Another line\n")
f.close()

f.read('newfile.txt', 'r')
print f.read()

I have tried to put f.close at the bottom of the code but I still get the same error.

The write part works if I comment out the f.read. It is failing on the f.read part.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Riaz Ladhani
  • 3,946
  • 15
  • 70
  • 127

3 Answers3

7

The line after f.close() that is f.read('newfile.txt', 'r') should be f = open('newfile.txt', 'r').

That is

f = open('newfile.txt', 'r')
print f.read()
f.close()

After which you need to add f.close() again.

Small Note

As in Python, the default value for 2nd arg of open is r, you can simple do open('newfile.txt')

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
2

You can't perform I/O operation on file_obj after closing it i.e.

file_obj.close()

So if you want to open the same file do:

if(file_obj.closed):
   file_obj = open(file_obj.name, file_obj.mode)

print (file.obj.read())
file_obj.close() 
Rishabh
  • 391
  • 3
  • 13
1

As illustrated above when you closed the file you need to open your file so that you can read it

f = open('newfile.txt', 'r')
print f.read()
f.close()
paul100
  • 148
  • 10