There are many inbuilt functions in python that allows you to perform read and write operations on the file like read(), write(), close() et. c. But while using these functions you may encounter ValueError: I/O operation on closed file error. In this tutorial, you will learn how to solve it easily.
What is ValueError?
ValueError is an exception error. It occurs when you try to pass the correct type of argument to the functions. But the value of the argument you are passing is not valid. For example, if functions accept the argument of type string but you are passing the invalid value of the string.
Why the ValueError: I/O operation on closed file Occurs
The most common reason for getting this I/O operation on a closed file error is that you are performing an input or output operations on the file that is already closed. For example, there is a text file with the filename “sample.txt” and I want to write something on it. I will get the error ValueError: I/O operation on closed file as the text file is already closed and performing writing on it.
You will get the error when you will run the below lines of code.
f = open("sample.txt") f.close() f.write("sample.txt")
Solution for I/O operation on closed file
The solution for not getting this error is very simple. If you want to perform a read or write operation on a file then first make sure the file is open for performing input or output operations. To check that use the if statement.
The following lines of code will not raise the error if you do write an operation after the file is closed.
f = open("sample.txt") f.close() if not f.close: f.write("sample.txt") print("file is open") print("file is closed")
You can see in the output the file is closed so you have to first open the file to perform a write operation.
The other way to avoid this error is to use the try and catch exception. Put the input and output performing code inside the try block and print output to the screen with the message “File is close ” inside the except block.
Execute the below lines of code to avoid this error.
f = open("sample.txt") f.close() try: f.write("sample.txt") except ValueError: print("file is closed")
ValueError is the most common error when you are passing the invalid value as an argument to the function. If you are getting the ValueError: I/O operation on a closed file then the above solutions will work for you.
I hope you have liked this tutorial. If you have any questions then you can c for more help.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.