[Tutor] Trying to extract the last line of a text file
János Juhász
janos.juhasz at VELUX.com
Fri Oct 20 09:01:27 CEST 2006
> Danny Yoo wrote:
> >
> >>>>> file('filename.txt').readlines()[-1]
> >>>> Not to hijack the thread, but what stops you from just putting a
> >>>> file.close() after your example line?
> >>> Which file should file.close() close? The problem is that we don't
> >>> have a handle on the particular file we want to close off.
> >>>
> >> Oh wow.. I totally missed that... nevermind.. ignore that question =D
> >
> >
> > Hi Chris,
> >
> Wow, that seems like overkill when you can just write
> f = open('filename.txt')
> f.readlines()
> f.close()
> In CPython (the regular Python that we usually talk about here,
> implemented in C) a file will be closed automatically as soon as there
> are no references to the file because CPython garbage collects objects
> immediately. This behaviour is not guaranteed by the language though and
> it is different in Jython.
> >
> >
> > This is similar in spirit to the idea of "autorelease" memory pools
used
> > by the Objective C language. We use some resource "manager" that does
> > keep a handle on resources. That manager then has the power and
> > responsiblity to call close() at some point. So one might imagine
doing
> > something like:
> >
> In Python 2.5 you can use with: to do this:
> with open('filename.txt') as f:
> f.readlines()
>
> f is guaranteed to be closed when the block exits.
> Kent
I made a small test about, what could happen with a file object,
that was opened for read, but left without closing.
# we need to put something into the test file
>>> fw1 = open(r'test.txt', 'w')
>>> fw1.write('written by fw1')
>>> fw1.close()
# so we have the test file
# we can open and read from it
>>> fr1 = open(r'test.txt', 'r')
>>> fr1.readlines()
['written by fw1']
# I left it opened.
# Another instance could be opened for read again
>>> fr2 = open(r'test.txt', 'r')
>>> fr2.readlines()
['written by fw1']
# I left the second instance opened eighter
# Someone rewrite the content of the file
>>> fw2 = open(r'test.txt', 'w')
>>> fw2.write('written by fw2')
>>> fw2.close()
# I closed it correctly after writing
# The instance opened for reading could be reread
>>> fr1.seek(0)
>>> fr1.readlines()
['written by fw2']
>>> fr2.readlines()
[]
# I have extended it a little
>>> fw2 = open(r'test.txt', 'w')
>>> fw2.write('written by fw2 but it is extended later')
>>> fw2.close()
>>> fr2.read()
' but it is extended later'
>>>
I feel that, we can left opened files with open(filename).readlines() in a
number of times,
but would be problematic to do it 100 000 times in the same script.
Yours sincerely,
______________________________
Janos Juhasz
More information about the Tutor
mailing list