[Tutor] rewriting script

Alan Gauld alan.gauld at btinternet.com
Sat Sep 8 09:19:47 CEST 2007


"Christopher Spears" <cspears2002 at yahoo.com> wrote 

>I have written a script that reads and displays text
> files:

> while True:
>    if os.path.exists(fname):
>        fobj = open(fname, 'r')
>        for eachLine in fobj:
>            print eachLine,
>            fobj.close()

> However, whenever I run the script, I get this result:

>    for eachLine in fobj:
> ValueError: I/O operation on closed file

You are closing the file inside the for loop, before you 
finish processing it. That is one reason why iterating 
over the file like this is often more helpful:

for line in open(fname):
    print line

because that will automatically close the file after 
you are done iterating.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list