473,394 Members | 1,794 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Opening files without closing them

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

Mar 5 '06 #1
15 1644
Sandra-24 wrote:
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
Mar 5 '06 #2
Marcin Mielżyński wrote:
Sandra-24 wrote:
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


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

sorry for spam

lopex
Mar 5 '06 #3
Sandra-24 wrote:
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
ro*********@gmail.com

"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

Mar 5 '06 #4
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:
try: .... f = open('file_that_doesnt_exists.ext')
.... finally:
.... f.close()
....
Traceback (most recent call last):
File "<stdin>", line 4, in ?
NameError: name 'f' is not defined

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.
Mar 5 '06 #5
Robert Kern wrote:
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.


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()

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
Who, my friend, can scale heaven?
-- _Gilgamesh_, ca. 3rd C. BC
Mar 6 '06 #6
Erik Max Francis wrote:
Robert Kern wrote:
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.


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
ro*********@gmail.com

"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

Mar 6 '06 #7
Sandra-24 wrote:
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
from __future__ import with_statement
with open('readme.txt') as f: .... contents = f.read()
.... f

<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
Mar 6 '06 #8
"Erik Max Francis" <ma*@alcyone.com> wrote in message
news:wP******************************@speakeasy.ne t...
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
Mar 6 '06 #9
"3c273" <no****@nospam.com> writes:
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.


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.
Mar 6 '06 #10
Paul Rubin wrote:
"3c273" <no****@nospam.com> writes:
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.


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
ro*********@gmail.com

"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

Mar 6 '06 #11
"Robert Kern" <ro*********@gmail.com> wrote in message
news:ma***************************************@pyt hon.org...
Paul Rubin wrote:
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.


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
Mar 7 '06 #12
3c273 wrote:
"Robert Kern" <ro*********@gmail.com> wrote in message
news:ma***************************************@pyt hon.org...
Paul Rubin wrote:
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.

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

Mar 7 '06 #13
Peter Hansen wrote:
3c273 wrote:
"Robert Kern" <ro*********@gmail.com> wrote in message
news:ma***************************************@pyt hon.org...
Paul Rubin wrote:

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.


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


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

Mar 8 '06 #14
"Peter Hansen" <pe***@engcorp.com> wrote in message
news:ma***************************************@pyt hon.org...

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
Mar 8 '06 #15

"Bryan" <be****@gmail.com> wrote in message
news:ma***************************************@pyt hon.org...
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
Mar 8 '06 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Peter Brown | last post by:
Hello! I am stepping through a text book that sets up different websites. The one I am testing is user registration. I set up the scripts and this is what I observe: Login (verifying...
1
by: DeeVee | last post by:
I am very new to the language. I am trying to open up to ten files from a list of many data files and writing them all to one big file. To do this I am getting them individually from the console...
6
by: MAB71 | last post by:
There should be a way to copy an access database ( .mdb file ) without closing connections to it. Unfortunately the FileCopy statement in VB gives an error if users are connected to the db. But I...
5
by: nick_faye | last post by:
Hi, I am still a newbie to VB and using MS Access 2000. I am currently trying to provide a preview of reports before printing them. My program is simple: AC.DoCmd.OpenReport "MyReport",...
14
by: cage | last post by:
hello can i write a eof to a file descriptor without closing it? like: fd.write(EOF) or something grts, ruben
1
by: sandeepk84 | last post by:
hi all... is there any way to open a new aspx page from another without closing the existing one? means, i have some controls in the first page and i need them to b there after doing some...
2
by: Luqman | last post by:
How can I open another WebForm in ASP.Net / VS 2005 without closing the Current Webform. I tried using Server.Transfer("Form2.Aspx",True) on Button_Click of Form1 but it close the current web...
34
by: Alexnb | last post by:
Gerhard Häring wrote: No, it didn't work, but it gave me some interesting feedback when I ran it in the shell. Heres what it told me: Traceback (most recent call last): File...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.