How to read lines from end of a file?
Darrell
news at dorb.com
Wed Dec 22 21:02:04 EST 1999
"Alexander Williams" <thantos at chancel.org> in message
news:slrn862rtb.732.thantos at chancel.org
was concerned about maxLen and half written lines.
Good idea the test for a trailing CR, added that.
Maybe maxLen should be sys.maxint by default. Then paranoid or performance
concerned, can tone it down from there.
import sys
def readLinesFromEnd(fn, maxLen=sys.maxint):
"""
Read lines from the end of a file up to a max number of bytes.
fn:: file name to read from
maxLen:: max number of bytes to read
"""
fp=open(fn)
# seek to the end
fp.seek(0,2)
# seek back from the end
fp.seek(-min(maxLen,fp.tell()),2)
# Dump the first line
# It might be chopped off
lines=fp.readlines()[1:]
if lines[-1][-1] != '\012':
# The last line might be half written.
lines=lines[:-1]
return lines
def main():
print readLinesFromEnd(sys.argv[1])
--
--Darrell
More information about the Python-list
mailing list