ValueError: I/O operation on closed file in Python 3

Dung Do Tien Jul 12 2022 33

Hello everyone.

I have created a small app with Python 3.10 and I have a CSV file that needs to be read and displayed in some format. It is simple like this:

 import csv
data = open("data-coin.csv", "r")
read_file = csv.reader(data)
data.close()
for p in read_file:
    print(f'Coin name: {p[0]}, Position: {p[1]}, Value: {p[2]} MeV')

But it throws an exception ValueError: I/O operation on closed file. Below is the detail of that exception.

 Traceback (most recent call last):
  File "main.py", line 5, in <module>
    for p in read_file:
ValueError: I/O operation on closed file.


** Process exited - Return Code: 1 **
Press Enter to exit terminal

I installed Python version 3.10 and window 11.

Thanks for any suggestions.

Have 1 answer(s) found.
  • J

    Jakub Szumiato Jul 12 2022

    This error threw because you read data after the file is closed. Please don't close the stream file before reading the data of it. 

    Here is a solution for you:

     import csv
    particles = open("data-coin.csv", "r")
    read_file = csv.reader(particles)
    for p in read_file:
        print(f'Coin name: {p[0]}, Position: {p[1]}, Value: {p[2]} MeV')
    
    particles.close()

    #Output

     Coin name: BTC, Position: 1, Value:  22000 MeV
    Coin name: ETH, Position: 2, Value: 1100 MeV
    Coin name: USDT, Position: 3, Value: 1 MeV
    Coin name: DOT, Position: 4, Value: 7.5 MeV
    Coin name: MATIC, Position: 5, Value: 0.56 MeV
    Coin name: NEAR, Position: 6, Value: 3.45 MeV
    Coin name: NRM, Position: 7, Value: 17 MeV
    Coin name: AMP, Position: 8, Value: 0.5 MeV
    Coin name: USDC, Position: 9, Value: 1 MeV
    
    
    ** Process exited - Return Code: 0 **
    Press Enter to exit terminal

    Hope this is helpful for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close