Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tail on python. Best performance implementation

I'm newbie to programming and in Python as well.
I wrote a function that implements the unix's tail:

def tail(file):
    strin = open(file, 'r')
    lis = strin.readlines()
    lastline = lis[-1]
    return lastline
    strin.close()

But I think that it is not optimal in performance.
How can I improve?

like image 778
phar1no Avatar asked May 01 '26 15:05

phar1no


1 Answers

You can use this Recipe from Collections.deque

def tail(filename, n=10):
    'Return the last n lines of a file'
    return deque(open(filename), n)

Refer this :- https://docs.python.org/2/library/collections.html#deque-recipes

like image 66
Vishnu Upadhyay Avatar answered May 04 '26 03:05

Vishnu Upadhyay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!