Opening files without closing them

S

Sandra-24

I was reading over some python code recently, and I saw something like
this:

contents = open(file).read()

And of course you can also do:

open(file, "w").write(obj)

Why do they no close the files? Is this sloppy programming or is the
file automatically closed when the reference is destroyed (after this
line)? I usually use:

try:
f = open(file)
contents = f.read()
finally:
f.close()

But now I am wondering if that is the same thing. Which method would
you rather use? Why?

Thanks,
Sandra
 
G

Guest

Sandra-24 said:
I was reading over some python code recently, and I saw something like
this:

contents = open(file).read()

And of course you can also do:

open(file, "w").write(obj)

Why do they no close the files? Is this sloppy programming or is the
file automatically closed when the reference is destroyed (after this
line)? I usually use:

try:
f = open(file)
contents = f.read()
finally:
f.close()

this above is equivalent to:

open(file){|f|
contents=f.read
}

the logic taking care of everything is encapsulated in open.

but can be done in less ruby way way :)



lopex
 
R

Robert Kern

Sandra-24 said:
I was reading over some python code recently, and I saw something like
this:

contents = open(file).read()

And of course you can also do:

open(file, "w").write(obj)

Why do they no close the files? Is this sloppy programming or is the
file automatically closed when the reference is destroyed (after this
line)?

Both!

Usually, the files will probably be closed *if* you are using CPython. However,
there is absolutely no guarantee of this behavior. For example, Jython uses a
different garbage collection scheme, and the files will *not* close immediately.
Future versions of CPython may have different behavior, too.
I usually use:

try:
f = open(file)
contents = f.read()
finally:
f.close()

But now I am wondering if that is the same thing. Which method would
you rather use? Why?

Just keep doing what you are doing, please.

--
Robert Kern
(e-mail address removed)

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
 
G

Guest

Marcin said:
this above is equivalent to:

open(file){|f|
contents=f.read
}

the logic taking care of everything is encapsulated in open.

but can be done in less ruby way way :)



lopex

Oops I thought I was writing to c.l.ruby :D

sorry for spam

lopex
 
E

Erik Max Francis

Robert said:
Just keep doing what you are doing, please.

Note quite. The assignment of the resources to its variable needs to be
done before the try:

f = open(file)
try:
contents = f.read()
finally:
f.close()
 
R

Robert Kern

Erik said:
Note quite. The assignment of the resources to its variable needs to be
done before the try:

f = open(file)
try:
contents = f.read()
finally:
f.close()

Yes, you are correct.

--
Robert Kern
(e-mail address removed)

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
 
S

Steven Bethard

Sandra-24 said:
I was reading over some python code recently, and I saw something like
this:

contents = open(file).read()

And of course you can also do:

open(file, "w").write(obj)

Why do they no close the files? Is this sloppy programming or is the
file automatically closed when the reference is destroyed (after this
line)? I usually use:

try:
f = open(file)
contents = f.read()
finally:
f.close()

But now I am wondering if that is the same thing. Which method would
you rather use? Why?

In Python 2.5, you'll write::

with open(file) as f:
contents = f.read()

and Python will automatically close the file at the end of the
with-statement. Observe:

Python 2.5a0 (trunk:42857M, Mar 5 2006, 14:50:28) [MSC v.1310 32 bit
(Intel)] on win32.... contents = f.read()
....<closed file 'readme.txt', mode 'r' at 0x00B8BAA8>

Of course, you have to wait until August or so for Python 2.5:
http://www.python.org/peps/pep-0356.html

STeVe
 
B

Bruno Desthuilliers

Sandra-24 a écrit :
I was reading over some python code recently, and I saw something like
this:

contents = open(file).read()

And of course you can also do:

open(file, "w").write(obj)

Why do they no close the files? Is this sloppy programming or is the
file automatically closed when the reference is destroyed (after this
line)?

IIRC, the current CPython implementation takes care of closing file
objects that are no longer referenced. But this may not be true of other
implementations (think: Jython).
I usually use:

try:
f = open(file)
contents = f.read()
finally:
f.close()

But now I am wondering if that is the same thing.

Not quite:
.... f = open('file_that_doesnt_exists.ext')
.... finally:
.... f.close()
....
Traceback (most recent call last):
Which method would
you rather use?

For a quick script, the simplest one. For production code, it depends
too much on the context to give a definitive single answer.
 
3

3c273

Erik Max Francis said:
Note quite. The assignment of the resources to its variable needs to be
done before the try:

f = open(file)
try:
contents = f.read()
finally:
f.close()
Pardon the newbie question, but could you explain why? I have been doing it
the same way as the OP and would like to know the difference. Thank you.
Louis
 
P

Paul Rubin

3c273 said:
Pardon the newbie question, but could you explain why? I have been doing it
the same way as the OP and would like to know the difference. Thank you.

Say that the open is inside the try block. If the file can't be
opened, then 'open' raises an exception, 'f' doesn't get set, and then
the 'finally' clause tries to close f. f might have been previously
bound to some other file (which still has other handles alive) and so
the wrong file gets closed.
 
R

Robert Kern

Paul said:
Say that the open is inside the try block. If the file can't be
opened, then 'open' raises an exception, 'f' doesn't get set, and then
the 'finally' clause tries to close f. f might have been previously
bound to some other file (which still has other handles alive) and so
the wrong file gets closed.

And even if 'f' wasn't bound to anything, you will get a NameError instead of
the exception that you're really interested in seeing.

--
Robert Kern
(e-mail address removed)

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
 
3

3c273

Robert Kern said:
And even if 'f' wasn't bound to anything, you will get a NameError instead of
the exception that you're really interested in seeing.

Thanks to both of you. So in order to be thorough, should I be doing:
try:
f=open('file')
except: IOError:
print 'doesn't exist'
so_something_else_instead()

try:
contents = f.read()
finally:
f.close()

Thanks again.
Louis
 
P

Peter Hansen

3c273 said:
Thanks to both of you. So in order to be thorough, should I be doing:
try:
f=open('file')
except: IOError:
print 'doesn't exist'
so_something_else_instead()

try:
contents = f.read()
finally:
f.close()

Unfortunately, that would still have trouble if the first exception
handler was executed, since then you'd try read from f, which would fail
with another exception, and then you'd try to close f, and that would
probably fail and raise an exception that isn't caught anywhere.

So this is better, though probably excessive in small scripts:

try:
f = open('file')
except IOError:
# do something else
else:
try:
content = f.read()
finally:
f.close()

This takes advantage of "else" on try statements, which executes only if
the except statement is not executed.

-Peter
 
B

Bryan

Peter said:
Unfortunately, that would still have trouble if the first exception
handler was executed, since then you'd try read from f, which would fail
with another exception, and then you'd try to close f, and that would
probably fail and raise an exception that isn't caught anywhere.

So this is better, though probably excessive in small scripts:

try:
f = open('file')
except IOError:
# do something else
else:
try:
content = f.read()
finally:
f.close()

This takes advantage of "else" on try statements, which executes only if
the except statement is not executed.

-Peter

this is what i always do for files and other types of resources:


if it's a low-level routine, i usually let any exceptions bubble up to a higher
level routine that cares or knows what to do.

f = open('file')
try:
# do something
finally:
f.close()


if i really want to handle the exception, then i handle it at a conceptually
"higher" level by wrapping it in an exception which is basically what some
higher-level routine would do anyways.


try:
f = open('file)
try:
# do something
finally:
f.close()
except IOError:
# handle exceptions



bryan
 
3

3c273

Peter Hansen said:
So this is better, though probably excessive in small scripts:

try:
f = open('file')
except IOError:
# do something else
else:
try:
content = f.read()
finally:
f.close()

This takes advantage of "else" on try statements, which executes only if
the except statement is not executed.
Thank you for your reply. I had forgotten that you could use 'else' in a
'try' statement. I like this solution. Thanks again.
Louis
 
3

3c273

Bryan said:
if i really want to handle the exception, then i handle it at a conceptually
"higher" level by wrapping it in an exception which is basically what some
higher-level routine would do anyways.


try:
f = open('file)
try:
# do something
finally:
f.close()
except IOError:
# handle exceptions
I like this idea also. Thanks to all who helped me understand..
Louis
 

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,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top