Python Forum

Full Version: Searching string in file and save next line
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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()
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
It works, thanks a lot!