Python Forum
[Answered] Retrieve a set of rows from text file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Answered] Retrieve a set of rows from text file
#1
Good evening !

I would like to retrieve all lines from string1 to string2, string3 to string4 and string5 to string6.
The file is 3000+ lines and the strings has no fixed line number.

Could you tell me a good approach to retrieve these set of rows ?
Thanks !


  .
  .
  string1
  .
  .
  string2
  .
  .
  .
  .
  string3
  .
  string4
  .
  .
  .
  .
  string5
  .
  .
  string6
  .
  .
Reply
#2
knob Wrote:Could you tell me a good approach to retrieve these set of rows ?
I suggest to read the file as a sequence of lines and compare the lines with the given strings.
Reply
#3
I would create a "toggle" tracking whether you are "inside" or "outside". An iterator for the list of sentinel lines would be helpful as well.

Then loop over all the lines. If you're "inside", print the line. If the line matches your next sentinel, flip the toggle.
Reply
#4
The question has a lot in common with this thread: Extract a string between 2 words from a text file. Please have look and see if this helps you along.
Reply
#5
Thank you ibreeden and bowlofred for the suggestions and reference !
I was able to adapt the code provided as example and it worked fine !

Thank you !
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Converting a json file to a dataframe with rows and columns eyavuz21 13 4,515 Jan-29-2023, 03:59 PM
Last Post: eyavuz21
Thumbs Up Need to compare the Excel file name with a directory text file. veeran1991 1 1,132 Dec-15-2022, 04:32 PM
Last Post: Larz60+
  Reading Specific Rows In a CSV File finndude 3 992 Dec-13-2022, 03:19 PM
Last Post: finndude
  Modify values in XML file by data from text file (without parsing) Paqqno 2 1,692 Apr-13-2022, 06:02 AM
Last Post: Paqqno
  Converted Pipe Delimited text file to CSV file atomxkai 4 7,016 Feb-11-2022, 12:38 AM
Last Post: atomxkai
  The code I have written removes the desired number of rows, but wrong rows Jdesi1983 0 1,636 Dec-08-2021, 04:42 AM
Last Post: Jdesi1983
  rows from sql query need to write to a file as columns sjcsvatt 6 2,407 Oct-09-2021, 12:45 AM
Last Post: snippsat
  Pandas DataFrame combine rows by column value, where Date Rows are NULL rhat398 0 2,122 May-04-2021, 10:51 PM
Last Post: rhat398
  Indexing [::-1] to Reverse ALL 2D Array Rows, ALL 3D, 4D Array Columns & Rows Python Jeremy7 8 7,144 Mar-02-2021, 01:54 AM
Last Post: Jeremy7
  write mariadb table rows query to each file? shams 1 1,889 Feb-02-2021, 04:10 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