Slothworks
Slothworks

Reputation: 1081

Under which circumstances will the python f.readlines method fail?

I use the code below to read in a text file (always a few thousand lines long). Is the except Exception as e block unnecessary?

try:
        in_file=open(in_file,'rU')
        try:
            in_content=in_file.readlines()
        except Exception as e:
            sys.stderr.write('Error: %s\n' % e.message)
            sys.exit(1)
        finally:
            in_file.close()
except IOError:
        sys.stderr.write('I/O Error: Input file not found.')
        sys.exit(1)

Also please tell me of the circumstances under which the file.readlines() method in Python will fail?

Upvotes: 3

Views: 3433

Answers (2)

Mike Müller
Mike Müller

Reputation: 85462

The pythonic way to read file looks like this:

with open(in_file_name,'rU') as in_file:
    in_content = in_file.readlines()

This should give you all the benefits of your code. So you don't need to worry about what kind of errors can occur. Python will take care of it. A file opened using the with statement will be closed in case of an exception.

Upvotes: 0

Untitled123
Untitled123

Reputation: 1293

I believe that IOError is the only possible thing that can happen. This covers both the file not existing and inadequate permissions. Any python reference I have seen only has IOError with files :). I'm not sure by what you mean with the stack trace, since it seems to just print the error itself?

import sys
try:
    with open("in_file",'rU') as in_file:
        in_content=in_file.readlines()
except Exception as e: #Should be replaceable with IOError, doesn't hurt to not 
    sys.stderr.write('%s\n' % e)
    sys.exit(1)

Upvotes: 1

Related Questions