Register Login

ValueError: I/O operations on closed file

Updated Feb 25, 2020

ValueError: I/O operations on closed file.

In this article, we’ll learn about what happens when we try to perform operations on closed files?

When the file is open we can perform operations on a file without an issue. But what if we try to write to a file when the file is closed?

Well, when we try to do so an error “ValueError: I/o operations on closed file” is raised. Let’s discuss it more briefly with the help of an example.

Example:

# Creating a file 'MyFile'
f = open("MyFile",'w')

# Entering data after opening the file
f.write("Hello this is my first file\n")
f.write("lets us learn about the error : ")
f.write("I\O operations on closed file")

# Closing the file
f.close()

# Entering data after closing the file
f.write("Hello")

In the above example first, we open a file  “MyFile” using ‘w’ mode (write). We know when we open a file using ‘w’ mode it’ll check if the file previously exists or not. If it does not it’ll create a new file with the same name.

After the file has created we entered some data into it using the write() method. After the data has been entered we closed the file using the close() method. Then again if we try to write something into the file after it has been closed it’ll raise a below-mentioned error.

ValueError: I/O operations on closed file.

I/O Operations On Closed Files

Solution:

To avoid this error, we have to open the file again if we want to add new data to it.

Example:

#Creating a file MyFile
f = open("MyFile",'w')

#Entering data after opening the file
f.write("Hello this is my first file\n")
f.write("lets us learn about the error : ")
f.write("I\O operations on closed file")

#closing the file
f.close()
f.open()

#opening the file again in append mode so previous data is not lost
f = open("MyFile",'a')
f.write("Hello again")


×