Search code examples
pythontxttail

Tail and search in txt file


I need to make a search on a txt file. Originally I've thought to open the file and search for the word I'm looking for on the last line

remote_file = sftp_client.open('file.txt')

try:
        lst = list(remote_file.readlines())
        lastlines=lst[len(lst) - 1]
        print(lastlines)
        if SEARCH_MASTER in lastlines:
            Master='Master_SX'
finally:
        remote_file.close()
        ssh.close()

This worked quite fine, but now I need to do something similar but on the last 5 lines of this file. I've tried to use the tail() function, adding the line

tailed_remote_file=remote_file.tail(3) 

but It gave me error

AttributeError: 'SFTPFile' object has no attribute 'tail'


Solution

  • There is no tail function in the python standard library. What I would suggest is a list slicing approach:

    n = 5
    lastlines = lst[-n:]
    for line in lastlines:
        if SEARCH_MASTER in line:
            Master='Master_SX'
    

    Further reading can be done here