text file edit object

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Jul 11 15:45:57 CEST 2003


Skip Montanaro <skip at pobox.com> wrote in
news:mailman.1057928298.10364.python-list at python.org: 

> Should be, though you have the obvious overhead of gulping the entire
> file. For very large files it would probably be more efficient to read
> the file in smaller chunks and only avoid writing the last ten lines. 
> However, the code gets that much more baroque. ;-)

It doesn't have to get terribly baroque:

def skiplast(n, iterable):
    """skiplast(n, iterable) -> iterator

    Yields all but the last n entries from the iterable"""
    buffer = []
    for value in iterable:
        buffer.append(value)
        if len(buffer) > n:
            yield buffer.pop(0)

Then you can do:

   infile = file("foo.txt", "r")
   outfile = file("foo.txt.new", "w")
   for line in skiplast(10, infile):
       outfile.write(line)
   infile.close()
   outfile.close()

Refactoring to avoid shuffling the data in the buffer is left as an 
exercise for anyone who feels it to be a problem.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list