Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError: readline of closed file in Python

Tags:

python

csv

This is my code:

import csv

with open('test.csv', 'rb') as csvfile:
    x = csv.reader(csvfile,delimiter=',',quotechar='|')

for row in x:
    print (row)

I get the following error:

ValueError: readline of closed file

What might be the problem?

like image 490
SZA Avatar asked Jan 27 '15 14:01

SZA


1 Answers

Your indent is out of order

import csv

with open('test.csv', 'rb') as csvfile:
    x = csv.reader(csvfile,delimiter=',',quotechar='|')

    for row in x:
        print (row)

Is the correct indent

The line, with open('test.csv', 'rb') as csvfile: creates a file object, but calls the __close__ method of the file once its block ends. As in Python, an un-indent closes the block, you have exited the block when you write for row in x:. Thus x is now closed, and you cannot perform any operations on that.

like image 176
Bhargav Rao Avatar answered Oct 03 '22 00:10

Bhargav Rao