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
  Open/save file on Android frohr 0 315 Jan-24-2024, 06:28 PM
Last Post: frohr
  how to save to multiple locations during save cubangt 1 543 Oct-23-2023, 10:16 PM
Last Post: deanhystad
  Need to replace a string with a file (HTML file) tester_V 1 761 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  save values permanently in python (perhaps not in a text file)? flash77 8 1,204 Jul-07-2023, 05:44 PM
Last Post: flash77
  splitting file into multiple files by searching for string AlphaInc 2 881 Jul-01-2023, 10:35 PM
Last Post: Pedroski55
  File "<string>", line 19, in <module> error is related to what? Frankduc 9 12,545 Mar-09-2023, 07:22 AM
Last Post: LocklearSusan
  Save and Close Excel File avd88 0 3,014 Feb-20-2023, 07:19 PM
Last Post: avd88
  Getting last line of each line occurrence in a file tester_V 1 857 Jan-31-2023, 09:29 PM
Last Post: deanhystad
  Save multiple Parts of Bytearray to File ? lastyle 1 939 Dec-10-2022, 08:09 AM
Last Post: Gribouillis
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,367 Sep-27-2022, 01:38 PM
Last Post: buran

Forum Jump:

User Panel Messages

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