Method of tail n Viewing Log File by Python Programming

  • 2021-07-10 20:26:56
  • OfStack

1. Function implementation


# -*- coding: utf-8 -*-

def tail(filename, n=10):
  with open(filename, "r") as f:
    lines = f.readlines()[-n:]

  return "".join(lines)

2. Test files

poetry. txt for ease of validation, precede each line with a line number


1.  Yu Meiren Yizhou sees Mei Zuo 
2.
3.  Song Dynasty: Huang Tingjian 
4.
5.  Message comes from the south to the end of the sky. 
6.  When mumes burst open, spring is nigh. 
7.  At dead of night the wind is slight, your fragrance late. 
8.  Don't open all over at dawn, branch to the south. 
9.
10.  You're envied by powder of the Terrace of Jade. 
11.  You waft amid the brows and will not fade. 
12.  Wish a cup deep in my life. 
13.  Go to the country 10 Old age, young heart. 
14.

3. Test results


print(tail("poetry.txt", 5))

"""

n=1
14.


n=3
12.  Wish a cup deep in my life. 
13.  Go to the country 10 Old age, young heart. 
14.


n=5
10.  You're envied by powder of the Terrace of Jade. 
11.  You waft amid the brows and will not fade. 
12.  Wish a cup deep in my life. 
13.  Go to the country 10 Old age, young heart. 
14.
"""


Related articles: