-1

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'

Inuyasha84
  • 50
  • 9

2 Answers2

2

some points to make your code better:

  1. lst[len(lst) - 1]: if you want to obtain last element of a list, just use -1, lst[-1], for second element from last: lst[-2] and so on

  2. if you want 5 first elements, you can use slices: lst[:5] and for 5 last elements: lst[-5:]

  3. readlines() return list and don't need to convert it to list

  4. instead of use remote_file.close() in finally, it is better to code like:

 with sftp_client.open('file.txt') as remote_file:

it closes the file automatically at the end

join:

if SEARCH_MASTER in " ".join(lst[-5:]):
    Master='Master_SX'

MoRe
  • 2,296
  • 2
  • 3
  • 23
1

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

YoshiMbele
  • 767
  • 1
  • 12
  • I think it is better to use `join` instead of `for` loop... – MoRe Jun 23 '22 at 13:14
  • ok this works fine!thanks. I still have a question how can I start the reading from the last line? in my case can happen that the "SEARCH_MASTER" can be find in multiple lines while I'm interested in the last one only. Thanks again – Inuyasha84 Jun 23 '22 at 13:26
  • 1
    just loop over `lastlines.reverse()` or via slicing again `lastlines[::-1]` – YoshiMbele Jun 23 '22 at 13:28