[Tutor] Trying to extract the last line of a text file
Chris Hengge
pyro9219 at gmail.com
Fri Oct 20 04:30:04 CEST 2006
More on that.. some of the file I work with are thousands of lines long...
one is even 10's of thousands.. so reading the entire thing into ram is MUCH
faster then reading line by line with the filestream open.
On 10/19/06, Chris Hengge <pyro9219 at gmail.com> wrote:
>
> I dont care for slow... I dont use computers with less then 1gb of ram..
> (all my systems have 2gb), I hate to wait... =D If I've got memory to use, I
> intend to use it!
>
> As for reading 100 20mb files, I'd do one at a time, then dump the
> variable storing the data, or reset/re-use. Just my take though.
>
> On 10/19/06, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
> >
> > Chris Hengge wrote:
> > > I thought my solution was the easiest.. but I guess everyone skipped
> > it =P
> > No, we didn't skip it,
> > but as we're all programmers here, we showed alternate ways that it
> > could be done.
> > Your post is the one that sparked the whole 'garbage collection' thing,
> > you'll notice.
> >
> > Now, I don't want to be left out of the loop on this,
> > and the first thing I thought of when I read his question about how to
> > read the last line was:
> > Well, what if he wants to read the last line of 100 20 mb files?
> > Does he really want to read all of these into memory just to get the
> > last line?
> > I wouldn't think so!
> > So I've made an alternate solution using seek.
> > The last line can't be more than 1000 chars long, or whatever the Python
> > maximum recursion depth happens to be at runtime,
> > but you could easily change this into a non-recursive implementation if
> > you so desired.
> > I just wanted to be cool :)
> >
> > #read_last_line.py
> > f = file('wii.txt','r')
> > f.seek(-1,2)#start at end of file.
> > if f.read(1) == '\n':#if file ends with a newline:
> > f.seek(-3,1)#start at right before the newline.
> > else:
> > f.seek(-1,1)#just start at the end.
> > def prevchar(fileobj):
> > achar = fileobj.read(1)
> > if achar == '\n': return ''
> > else:
> > fileobj.seek(-2,1)
> > return prevchar(fileobj)+achar
> > print prevchar(f)
> >
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20061019/5b695fe0/attachment.htm
More information about the Tutor
mailing list