[Tutor] rewriting script

Steve Willoughby steve at alchemy.com
Sat Sep 8 07:51:32 CEST 2007


Christopher Spears wrote:
> 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()

You're closing the file after reading the first line.  You want
that fobj.close() line to be outside the for loop (outdent one level)




More information about the Tutor mailing list