how do you know if open failed?

S

SpreadTooThin

f = open('myfile.bin', 'rb')

How do I know if there was an error opening my file?
 
F

Fredrik Lundh

SpreadTooThin said:
f = open('myfile.bin', 'rb')

How do I know if there was an error opening my file?

you'll notice:
Traceback (most recent call last):

</F>
 
N

Neil Cerutti

f = open('myfile.bin', 'rb')

How do I know if there was an error opening my file?

Try it an see.

Seriously, it will raise an exception that you can catch.

try:
f = open('myfile.bin', 'rb')
# Do stuff with f
except IOError, inst:
print 'Phooey.', inst.errno, inst.strerror
 
E

Erik Johnson

tobiah said:
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.
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
 
B

Bruno Desthuilliers

tobiah a écrit :
try:
open('noexist')
except:
print "Didn't open"

Should be:

try:
f = open('noexists')
except IOError, e:
print >> sys.stderr, "Failed to open 'noexists' : %s" % e
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top