Riaz Ladhani Riaz Ladhani - 4 months ago 32
Python Question

Python ValueError: I/O operation on closed file. sample tutorial not working

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.read('newfile.txt', 'r')
print f.read()

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

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


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

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