From a0e0b03bbb1af2496841ffe824b36c5c59fed759 Mon Sep 17 00:00:00 2001 From: pin Date: Wed, 7 Jul 2010 12:24:05 +0000 Subject: [PATCH 1/1] =?utf8?q?Ajout=20utilitaire=20pour=20lire=20les=20fic?= =?utf8?q?hiers=20ligne=20par=20ligne=20=C3=A0=20l'envers.?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit git-svn-id: https://svn.cri.ensmp.fr/svn/minwii/trunk@276 fe552daf-6dbe-4428-90eb-1537e0879342 --- src/minwii/backwardsfilereader.py | 47 +++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100755 src/minwii/backwardsfilereader.py diff --git a/src/minwii/backwardsfilereader.py b/src/minwii/backwardsfilereader.py new file mode 100755 index 0000000..ff89f07 --- /dev/null +++ b/src/minwii/backwardsfilereader.py @@ -0,0 +1,47 @@ +## {{{ http://code.activestate.com/recipes/439045/ (r2) +#!/usr/bin/env python +# -*-mode: python; coding: iso-8859-1 -*- +# +# Copyright (c) Peter Astrand +# $Id$ +# $URL$ + +import string + +class BackwardsReader: + """Read a file line by line, backwards""" + + def readline(self): + while 1: + newline_pos = string.rfind(self.buf, "\n") + pos = self.file.tell() + if newline_pos != -1: + # Found a newline + line = self.buf[newline_pos+1:] + self.buf = self.buf[:newline_pos] + if pos != 0 or newline_pos != 0 or self.trailing_newline: + line += "\n" + return line + else: + if pos == 0: + # Start-of-file + return "" + else: + # Need to fill buffer + toread = min(self.BLKSIZE, pos) + self.file.seek(-toread, 1) + self.buf = self.file.read(toread) + self.buf + self.file.seek(-toread, 1) + if pos - toread == 0: + self.buf = "\n" + self.buf + + def __init__(self, file, BLKSIZE=4096): + self.file = file + self.BLKSIZE = BLKSIZE + self.buf = "" + self.file.seek(-1, 2) + self.trailing_newline = 0 + lastchar = self.file.read(1) + if lastchar == "\n": + self.trailing_newline = 1 + self.file.seek(-1, 2) -- 2.20.1