0

I'm looking for a string str in a file and need the line after the occurrence of str. Right now, I am opening a file, reading all lines, saving them to a list and then looking up for that string in a list. Here's my code:

with open(file,'r') as file1:
    data = file1.readlines()

for num, line in enumerate(data,1):
    if 'str' in line:
        print line, data[num+1] 

I know that str will be somewhere in the last 10 lines in file. So, I want to read and save the last 10 lines as a list rather than the whole file in the data variable.

I don't want to do $tail file.dat > file1.dat and go from there.

I want something like reversed(readlines()) and save 10 lines to a list. How do I do it?

nac001
  • 693
  • 2
  • 9
  • 18
  • 1
    `reversed(readlines())[:10]` – Joran Beasley Dec 11 '18 at 19:42
  • I don't think the author really wants to save the lines reversed (last line first, and son). She wants to save the lines after the occurrence of `'str'` and preserve the order. – Pandemonium Dec 11 '18 at 19:48
  • @Pie'Oh'Pah, that's right. I want the `len(data)` to be 10 and work from there. – nac001 Dec 11 '18 at 19:51
  • python has negative integers. You can loop through a range of 10 and then store line[-i] – octopathTraveller Dec 11 '18 at 19:54
  • @Jérôme, `data = file1.readlines()[:-10]` reads the whole file except the last 10 lines. – nac001 Dec 11 '18 at 20:54
  • @nacc001 said these: "'str' is somewhere in the last 10 lines" and "...need the lines after the occurrence of 'str'" but somehow later asked to "...save the last 10 lines as a list" a more complete answer can only be given when this conflict is cleared. – Pandemonium Dec 11 '18 at 20:55
  • @nac001 You should have stated that you wanted to "save the rest of the lines in a file after an occurrence of 'str' as a list". The unclear statements made this question closed as being a duplicate. – Pandemonium Dec 11 '18 at 20:59
  • I need the first 10 lines from the output of [this](https://stackoverflow.com/a/2301792/9639680) answer. I can put it in a list. – nac001 Dec 11 '18 at 21:07

0 Answers0