3

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?

Slothworks
  • 1,083
  • 14
  • 18
  • Why do you want write the error message into `stderr` manually instead of just raise the error? – Remi Guan Jan 01 '16 at 07:29
  • I could do that. But I just thought I'd print a user friendly message rather than `raise` which will print the entire traceback. – Slothworks Jan 01 '16 at 07:39

2 Answers2

1

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)
Untitled123
  • 1,317
  • 7
  • 20
  • I think so too :) Thats the only thing that the documentation says too. Although maybe it would be interesting to look at the [source code](http://stackoverflow.com/a/11385592/3262406) too. But I'm not really sure where I must look. And I meant the stack trace for the case when I `raise` an exception instead of writing to `stderr`. – Slothworks Jan 07 '16 at 06:05
0

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.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161