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
#1
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()
Reply
#2
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
Reply
#3
It works, thanks a lot!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  append a string to a modified line Mr_Blue 10 582 Sep-16-2021, 07:24 PM
Last Post: Mr_Blue
  How to capture string from a line to certain line jerald 1 454 Jun-30-2021, 05:13 PM
Last Post: Larz60+
  [Solved] Reading every nth line into a column from txt file Laplace12 7 955 Jun-29-2021, 09:17 AM
Last Post: Laplace12
  help with project of reading and searching big log file korenron 6 482 Jun-24-2021, 01:57 PM
Last Post: korenron
  How to save Matplot chart to temp file? Morkus 2 846 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 897 Jun-04-2021, 01:28 PM
Last Post: snippsat
  How to save some results in .txt file with Python? Melcu54 4 1,486 May-26-2021, 08:15 AM
Last Post: snippsat
  How to design a save file format? philipbergwerf 5 1,258 Apr-26-2021, 07:39 PM
Last Post: Gribouillis
Exclamation Why there's a 'blank line' on CSV file? brunolelli 4 977 Mar-25-2021, 03:43 AM
Last Post: buran
  How to create new line '/n' at each delimiter in a string? MikeAW2010 3 838 Dec-15-2020, 05:21 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

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