If you try to access a closed file, you will raise the ValueError: I/O operation on closed file. I/O means Input/Output and refers to the read and write operations in Python.
To solve this error, ensure you put all writing operations before closing the file.
This tutorial will go through how to solve this error with code examples.
Table of contents
ValueError: I/O operation on closed file
In Python, a value is information stored within a particular object. You will encounter a ValueError in Python when you use a built-in operation or function that receives an argument with the right type but an inappropriate value.
A file is suitable for I/O operations, but a closed file is not suitable for I/O operations.
Why Close Files in Python?
- File operations is a resource in programming. If you have multiple files open, you are using more resources, which will impact performance.
- If you are making editions to files, they often do not go into effect until after the file is closed.
- Windows treats open files as locked; you will not be able to access an open file with another Python script.
Let’s look at examples of the ValueError occurring in code and solve it.
Example #1: Accessing a Closed File
Consider the following CSV file called particles.csv that contains the name, charge and mass of three particles:
electron,-1, 0.511 muon,-1,105.7 tau,-1,1776.9
Next, we will write a program that will read the information from the CSV file and print it to the console. We will import the csv library to read the CSV file. Let’s look at the code:
import csv particles = open("particles.csv", "r") read_file = csv.reader(particles) particles.close() for p in read_file: print(f'Particle: {p[0]}, Charge: {p[1]}, Mass: {p[2]} MeV')
We create a TextIOWrapper object called particles. This object is a buffered text stream containing the file’s text. We then access each line in particles using a for loop. Let’s run the code to see what happens:
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) 7 particles.close() 8 ----≻ 9 for p in read_file: 10 11 print(f'Particle: {p[0]}, Charge: {p[1]}, Mass: {p[2]} MeV') ValueError: I/O operation on closed file.
The error occurs because we close the file before we iterate over it.
Solution
To solve this error, we need to place the close() after the for loop. Let’s look at the revised code:
import csv particles = open("particles.csv", "r") read_file = csv.reader(particles) for p in read_file: print(f'Particle: {p[0]}, Charge: {p[1]}, Mass: {p[2]} MeV') particles.close()
Particle: electron, Charge: -1, Mass: 0.511 MeV Particle: muon, Charge: -1, Mass: 105.7 MeV Particle: tau, Charge: -1, Mass: 1776.9 MeV
The code successfully prints the particle information to the console.
Example #2: Placing Writing Outside of with Statment
The best practice to open a file is to use a with keyword. This pattern is also known as a context manager, which facilitates the proper handling of resources. Let’s look at an example of using the with keyword to open our particles.csv file:
import csv with open("particles.csv", "r") as particles: read_file = csv.reader(particles) for p in read_file: print(f'Particle: {p[0]}, Charge: {p[1]}, Mass: {p[2]} MeV')
Let’s run the code to see what happens:
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) 5 read_file = csv.reader(particles) 6 ----≻ 7 for p in read_file: 8 9 print(f'Particle: {p[0]}, Charge: {p[1]}, Mass: {p[2]} MeV') ValueError: I/O operation on closed file.
The error occurs because the loop over the file is outside of the with open() statement. Once we place code outside of with statement code block, the file closes. Therefore the for loop is over a closed file.
Solution
We need to place the for loop within the with statement to solve this error. Let’s look at the revised code:
import csv with open("particles.csv", "r") as particles: read_file = csv.reader(particles) for p in read_file: print(f'Particle: {p[0]}, Charge: {p[1]}, Mass: {p[2]} MeV')
Let’s run the code to see the result:
Particle: electron, Charge: -1, Mass: 0.511 MeV Particle: muon, Charge: -1, Mass: 105.7 MeV Particle: tau, Charge: -1, Mass: 1776.9 MeV
The code successfully prints the particle information to the console. For further reading on ensuring correct indentation in Python, go to the article: How to Solve Python IndentationError: unindent does not match any outer indentation level.
Example #3: Closing the File Within a for loop
Let’s look at an example where we open the file and print the file’s contents, but we put a close() statement in the for loop.
import csv particles = open("particles.csv", "r") read_file = csv.reader(particles) for p in read_file: print(f'Particle: {p[0]}, Charge: {p[1]}, Mass: {p[2]} MeV') particles.close()
Let’s run the code to see what happens:
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) 5 read_file = csv.reader(particles) 6 ----≻ 7 for p in read_file: 8 9 print(f'Particle: {p[0]}, Charge: {p[1]}, Mass: {p[2]} MeV') ValueError: I/O operation on closed file.
The error occurs because we close the file before iterating over every line in the file. The first iteration closes the file.
Solution
To solve this error, we need to place the close() statement outside of the for loop. Let’s run the code to get the result:
import csv particles = open("particles.csv", "r") read_file = csv.reader(particles) for p in read_file: print(f'Particle: {p[0]}, Charge: {p[1]}, Mass: {p[2]} MeV') particles.close()
Let’s run the code to see the result:
Particle: electron, Charge: -1, Mass: 0.511 MeV Particle: muon, Charge: -1, Mass: 105.7 MeV Particle: tau, Charge: -1, Mass: 1776.9 MeV
The code successfully prints the particle information to the console.
Summary
Congratulations on reading to the end of this tutorial! The error ValueError: I/O operation on a closed file occurs when you try to access a closed file during an I/O operation. To solve this error, ensure that you indent the code that follows if you are using the with statement. Also, only close the file after you have completed all iterations in a for loop by placing the filename.close() outside of the loop.
For further reading on ValueErrors, go to the article: How to Solve Python ValueError: could not convert string to float.
For further reading on errors involving reading or writing to files in Python, go to the article: How to Solve Python AttributeError: ‘str’ object has no attribute ‘write’
To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.
Have fun and happy researching!
Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.