last_lines_file.py 437 B

12345678910111213141516171819
  1. def tail(file, n=1, bs=1024):
  2. f = open(file)
  3. f.seek(0,2)
  4. l = 1-f.read(1).count('\n')
  5. B = f.tell()
  6. while n >= l and B > 0:
  7. block = min(bs, B)
  8. B -= block
  9. f.seek(B, 0)
  10. l += f.read(block).count('\n')
  11. f.seek(B, 0)
  12. l = min(l,n)
  13. lines = f.readlines()[-l:]
  14. f.close()
  15. return lines
  16. lines = tail("SampleTextFile_10kb.txt", 2)
  17. for line in lines:
  18. print (line)