By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,922 Members | 1,493 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,922 IT Pros & Developers. It's quick & easy.

how do you know if open failed?

P: n/a
f = open('myfile.bin', 'rb')

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

Sep 28 '06 #1
Share this Question
Share on Google+
5 Replies


P: n/a
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"

--
Posted via a free Usenet account from http://www.teranews.com

Sep 28 '06 #2

P: n/a
SpreadTooThin wrote:
f = open('myfile.bin', 'rb')

How do I know if there was an error opening my file?
you'll notice:
>>f = open("myfile.bin", "rb")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'myfile.bin'
>>>
</F>

Sep 28 '06 #3

P: n/a
On 2006-09-28, SpreadTooThin <bj********@gmail.comwrote:
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

--
Neil Cerutti
Sep 28 '06 #4

P: n/a

"tobiah" <to**@tobiah.orgwrote in message
news:45***********************@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
Sep 28 '06 #5

P: n/a
tobiah a écrit :
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"
Should be:

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

Sep 28 '06 #6

This discussion thread is closed

Replies have been disabled for this discussion.