Re: how do you know if open failed?




"tobiah" <toby@xxxxxxxxxx> wrote in message
news:451c0669$0$19689$88260bb3@xxxxxxxxxxxxxxxxxxxx
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


.



Relevant Pages

  • Re: petitions.pm.gov.uk - cycle lanes
    ... Do not fall into the trap of "cycle training is for children". ... OK, everyone except you, care to add any more exceptions? ... or repeating it because they didn't listen carefully enough? ...
    (uk.rec.cycling)
  • Re: petitions.pm.gov.uk - cycle lanes
    ... GeoffC wrote: ... Do not fall into the trap of "cycle training is for children". ... OK, everyone except you, care to add any more exceptions? ...
    (uk.rec.cycling)
  • Re: JSP problem..
    ... deployment descriptor to trap all Exceptions. ... It stops where you have a Java syntax error or try to use a null object. ... what I don't understand is that the same java code that ...
    (comp.lang.java.help)
  • Re: WebBrowser control error
    ... Exceptions, and check that Common Language Runtime Exceptions are set to ... I can't seem to trap that error. ... >> I fear you will have to live with this if you use the WebBrowser control. ...
    (microsoft.public.dotnet.languages.vb)
  • Re: .NET has a broken Exception model
    ... > a distinct difference. ... All exceptions inherit from System.Exception. ... Fatal exceptions as defined by the framework. ... >> so it's not really an issue to me, but if I wanted to trap those four ...
    (microsoft.public.dotnet.general)