473,386 Members | 1,694 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,386 software developers and data experts.

Closing files

I have recently started playing around with Python. Some of the things
I have done have involved reading files. The way I do this is along the
lines of

f = file('file.txt')
lines = f.readlines()
f.close()

I have noticed that it is possible to do this in one line:

lines = file('file.txt').readlines()

My question is: does the file get closed if I do the reading in this
manner?

Similarly, for reading the output from other programs or system
commands, I would do:

o = popen('executable')
lines = o.readlines()
o.close()

Is it OK to do this with a one-liner as well, with

lines = popen('executable').readlines()

without closing the file object?

Thanks,
Henrik Holm
Jul 18 '05 #1
6 2088
ne*******@henrikholm.com (Henrik Holm) writes:

[+]
I have recently started playing around with Python. Some of the things
I have done have involved reading files. The way I do this is along the
lines of

f = file('file.txt')
lines = f.readlines()
f.close()
Verbose and readable. A typical approach.

[+]
I have noticed that it is possible to do this in one line:

lines = file('file.txt').readlines()

My question is: does the file get closed if I do the reading in this
manner?
It appears to be closed on my Linux system as by using this shorthand
approach, you are not saving any reference to the file object.

Evidently, it is closed immediatly after the statement executes.
There's no point in the file staying open as you'd have no way to
refer to it any more.

[+]
Similarly, for reading the output from other programs or system
commands, I would do:

o = popen('executable')
lines = o.readlines()
o.close()

Is it OK to do this with a one-liner as well, with

lines = popen('executable').readlines()
My guess is that this is probably OK too. At least for simple cases.

My experience has been, that by going for maximum terseness, you
eventually get into trouble somehow.

YMMV

[+]
without closing the file object?
If you are going to have one or more references to the file or pipe
object, you must either close them or delete the reference to the
object using del().

If you are running on Unix, do some experimentation with the 'fuser'
or 'lsof' commands to see if the system is reporting the files open or
closed.

Or why not for fun;

while True:
file('/tmp/foo')

I bet this runs forever and you don't run out of open file descriptors
:-)
[+]
Thanks,
Henrik Holm


--
-------------------------------------------------------------------------------
Jerry Sievers 305 854-3001 (home) WWW ECommerce Consultant
305 321-1144 (mobile http://www.JerrySievers.com/
Jul 18 '05 #2
Henrik Holm wrote:
I have recently started playing around with Python. Some of the things
I have done have involved reading files. The way I do this is along the
lines of

f = file('file.txt')
lines = f.readlines()
f.close()

I have noticed that it is possible to do this in one line:

lines = file('file.txt').readlines()

My question is: does the file get closed if I do the reading in this
manner?


The file gets closed in CPython because file objects are closed when the
last reference to them gets deleted. (I guess when the .readlines ()
returns)

When you use Jython or IronPython, the file will be closed sometime
later when the file object gets garbage collected. This can lead to
problems becaause the process might run out of file handles before the
garbage collection and file locks are held a lot longer.

This led to two camps.

One camp thinks that the correct way would be
f = file('file.txt')
try:
lines = f.readlines()
finally:
f.close()

The other camp thinks that reference counting should be implemented in
all Python implementations.

And then there are a lot of people who think that changing all the
readlines one liner would be quite easy should the need of a Jython port
arrive, so why bother about it now?

Daniel
Jul 18 '05 #3
Daniel Dittmar wrote:
And then there are a lot of people who think that changing all the
readlines one liner would be quite easy should the need of a Jython port
arrive, so why bother about it now?


The problem with this approach is, when the time for the Jython port
arrives, do you remember to do it?

--
Timo Virkkala
Jul 18 '05 #4
Timo Virkkala wrote:
Daniel Dittmar wrote:
And then there are a lot of people who think that changing all the
readlines one liner would be quite easy should the need of a Jython
port arrive, so why bother about it now?


The problem with this approach is, when the time for the Jython port
arrives, do you remember to do it?


If you can write a unit test now that would fail using Jython, then
you're going to be reminded quickly.

And perhaps there will be changes to Python
- that make the oppen().readlines () version work in fully garbage
collected environments; like closing the inner file handle when the end
of the file is reached
- that suggest a different solution; like declarations on local
variables that say "call destructor when object goes out of scope"

Then, having more complicated code today doesn't buy you anything.

Daniel
Jul 18 '05 #5
Daniel Dittmar wrote:
- that suggest a different solution; like declarations on local
variables that say "call destructor when object goes out of scope"


You may be interested in PEP 310 (reliable acquisition/release pairs):
http://www.python.org/peps/pep-0310.html

(Although if that idea gets adopted, it is unlikely to use the 'with' keyword -
see PEP 3000 for the reason why)

Regards,
Nick.
Jul 18 '05 #6
> Daniel Dittmar wrote:
- that suggest a different solution; like declarations on local
variables that say "call destructor when object goes out of scope"

I did not follow all of this thread (that precise subject reoccurs
once in a while, with some regularity), but I merely would like to
point out that objects never go "out of scope". Only variables do,
and variables hold references to objects. When the last reference to
an object disappears, only then the destructor is called. With Python
(that particular Python that some call C-Python), this is guaranteed.

[Nick Coghlan] You may be interested in PEP 310 (reliable acquisition/release pairs):
http://www.python.org/peps/pep-0310.html


Such a PEP might be useful for Jython or other Python-like languages.
Yet with Python, the real thing, the effect of the PEP is easily
achieved by relying on the timely finalisation of objects. For example,
in Pymacs, the `let' and other various `save-' constructs of Emacs Lisp
are simulated through Let() objects, used like in this example:

let = Let().push_excursion()
if True :
... user code ...
del let

Here, the `if' sole-purpose is to indent the "with" block, and so, to
make the whole construct more legible.

--
François Pinard http://pinard.progiciels-bpi.ca
Jul 18 '05 #7

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

Similar topics

5
by: David Leon | last post by:
Is there any way to stop php.exe closing after it processes a PHP script? It doesn't seem to have the traditional options of an MS-DOS program. I am using Windows XP Pro and have associated .php...
4
by: dustin lee | last post by:
Over the years I've gotten out of the habit of explicitly closing file objects (whether for reading or writing) since the right thing always seems to happen auto-magically (e.g. files get written...
4
by: Max Dupenois | last post by:
I've seen numerous articles with similair (similar sp?) titles to this in my search.. unfortunately none of them seem to contain what i want, (or if they do i need someone to point out my stupidity...
6
by: Tim Barg | last post by:
I am using a CryptoStream to encrypt and then save an xml file. However, when reading it back in, I am getting a CryptographicException. I am hitting this because I have some large xml files ( >...
3
by: blakecaraway | last post by:
Hi there. I have a C# console application that extracts data to flat files. Some of my business partners begin consuming these extract files before I've had a chance to write the newest ones (I...
7
by: darrel | last post by:
We're running into a problem on our new site. Once a week or so, our site goes down with an 'out of memory error'. Rebooting the web server fixes things. Googling the error doesn't return many...
9
by: Ron | last post by:
my application is throwing an exception error when closing if I run a procedure in the app. I can't even trap the error with try/catch ex As Exception. Is there a way to completely shut down the...
3
by: Carroll, Barry | last post by:
Greetings: Please forgive me if this is the wrong place for this post. I couldn't find a more acceptable forum. If there is one, please point me in the right direction. I am part of a small...
6
by: Steven D'Aprano | last post by:
Closing a file can (I believe) raise an exception. Is that documented anywhere? I've spent a lot of frustrating time trying to track this down, with no luck, which suggests that either my...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
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,...

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.