Python Forum
Searching string in file and save next line
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Searching string in file and save next line
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
Line 2
Line 3

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


file = open(file.txt","r")
   for line_no, line in enumerate(file):
      if "Line 1" in line:
         position = line_no+1
file = open(file.txt","r")
   for line_no, line in enumerate(file):
      if line_no == position:
          results =  float(line.split()[0])
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
            if 'Line' in line:
                nxline = True
It works, thanks a lot!

Possibly Related Threads…
Thread Author Replies Views Last Post
  append a string to a modified line Mr_Blue 10 570 Sep-16-2021, 07:24 PM
Last Post: Mr_Blue
  How to capture string from a line to certain line jerald 1 447 Jun-30-2021, 05:13 PM
Last Post: Larz60+
  [Solved] Reading every nth line into a column from txt file Laplace12 7 942 Jun-29-2021, 09:17 AM
Last Post: Laplace12
  help with project of reading and searching big log file korenron 6 470 Jun-24-2021, 01:57 PM
Last Post: korenron
  How to save Matplot chart to temp file? Morkus 2 830 Jun-12-2021, 10:52 AM
Last Post: Morkus
  How to save modification of a file in original file not a new one? mjrezayani 3 886 Jun-04-2021, 01:28 PM
Last Post: snippsat
  How to save some results in .txt file with Python? Melcu54 4 1,452 May-26-2021, 08:15 AM
Last Post: snippsat
  How to design a save file format? philipbergwerf 5 1,244 Apr-26-2021, 07:39 PM
Last Post: Gribouillis
Exclamation Why there's a 'blank line' on CSV file? brunolelli 4 970 Mar-25-2021, 03:43 AM
Last Post: buran
  How to create new line '/n' at each delimiter in a string? MikeAW2010 3 827 Dec-15-2020, 05:21 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020