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

#!/usr/bin/env python

'readTextFile.py -- read and display text file'

import os

# get filename
while True:
    fname = raw_input('Enter file name: ')
    print
    if os.path.exists(fname):
        fobj = open(fname, 'r')
        for eachLine in fobj:
            print eachLine,
            fobj.close()
    else:
        print"*** File doesn't exist"
        break

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

[EMAIL PROTECTED] ./chap3 314> python readTextFile1.py
Enter file name: datefile

Fri Sep  7 22:13:03 PDT 2007
Traceback (most recent call last):
  File "readTextFile1.py", line 13, in ?
    for eachLine in fobj:
ValueError: I/O operation on closed file

The original script appeared in 'Core Python
Programming' in this form:

#!/usr/bin/env python

'readTextFile.py -- read and display text file'

# get filename
fname = raw_input('Enter file name: ')
print

# attempt to open file for reading
try:
    fobj = open(fname, 'r')
except IOError, e:
    print"*** file open error:", e
else:
    # display contents to the screen
    for eachLine in fobj:
        print eachLine,
    fobj.close()

I modified the script as an answer to one of the end
of chapter questions.  Basically, I am supposed to
rewrite the script, so that runs with 'try' and
'except'.

What is causing the error message?  I thought the file
was opened earlier in the script.
_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to