how do you know if open failed?

Erik Johnson ejatwellkeeperdotcom
Thu Sep 28 14:41:58 EDT 2006


"tobiah" <toby at tobiah.org> wrote in message
news:451c0669$0$19689$88260bb3 at free.teranews.com...
> SpreadTooThin wrote:
> > f = open('myfile.bin', 'rb')
> >
> > How do I know if there was an error opening my file?
> >
> try:
>          open('noexist')
> except:
>          print "Didn't open"

    That's a way to trap any exception. I think a better answer to the
question is "You'll know if it didn't work because Python throws exceptions
when it runs into problems." You can catch exceptions and try to do
something about them if you want to. Uncaught exceptions cause the
interpreter to exit with a stack trace. Sometimes that's the most logical
thing to do.

>>> fd = open('doesnt_exist', 'rb')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IOError: [Errno 2] No such file or directory: 'doesnt_exist'


It would throw a different exception if there were a permission problem, for
example.

-ej





More information about the Python-list mailing list