Python Forum
Searching string in file and save next line - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Searching string in file and save next line (/thread-28200.html)



Searching string in file and save next line - dani8586 - Jul-09-2020

Hello, I'm new to the forum so hello all! I've looked for the solution to my problem in the forum, but I didn't find it, so I ask. I apologize if this was already discussed and I've missed it. The problem I'm facing is the following. I have a file which looks like this

Line 1
34
Line 2
78
Line 3
88

and what I want to do is to read the file and when the string Line 1 and Line 3 are found, save the values 34 and 88. Unfortunately this file is generate by an external code, so I cannot modify this structure.

I wrote a code that works, but what I'm doing is looping twice on the file. I'm doing it in the following way. Firstly I find the line number where my string is, then in the second loop I save the string of the line number. Clearly this is inefficient for large files. Is there a way to do this in one single loop?

Thanks for the help

Daniele

file = open(file.txt","r")
   for line_no, line in enumerate(file):
      if "Line 1" in line:
         position = line_no+1
file.close()
##
file = open(file.txt","r")
   for line_no, line in enumerate(file):
      if line_no == position:
          results =  float(line.split()[0])
file.close()



RE: Searching string in file and save next line - Larz60+ - Jul-09-2020

this is not tested, but should work:
nxline = False
with open('file.txt') as fp:
    for line in fp:
        line = line.strip()
        if nxline:
            print(f"Got a number: {line}")
            nxline = False
        else:
            if 'Line' in line:
                nxline = True



RE: Searching string in file and save next line - dani8586 - Jul-10-2020

It works, thanks a lot!