ValueError: I/O operation on closed file

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu May 26 02:46:26 EDT 2016


On Thursday 26 May 2016 15:47, San wrote:

> Following is the code i used.
> 
> def test_results(filename):
>     import csv
>     with open(filename,"rU") as f:
>      reader = csv.reader(f,delimiter="\t")
>      result = {}

You should use more consistent indents. Can you set your editor to 
automatically use four spaces each time you hit the tab key?

In any case, you indent the "with" block. There are TWO lines indented, then 
you outdent again. That means the with block completes and the file is closed.

You have:

def test_restults(filename):
    ...
    with open(...) as f:
        indented block
    # f gets closed here
    for row in reader:
        indented block
    print result



What you should have is:

def test_restults(filename):
    ...
    with open(...) as f:
        indented block
        for row in reader:
            indented block
    # f gets closed here
    print result


-- 
Steve




More information about the Python-list mailing list