Working with a section in a text file in Python

advertisements

I am working on text files in Python and i am having difficulties in looping just a section of the text file, for example if i had a file like this:

     Hello my name is jason
     i am 25 and make 30,000 a year.
     this is the beginning.
     xxxxxxxxxxxxx
     xxxxxxxxxxxxx
     xxxxxxxxxxxxx
     xxxxxxxxxxxxx
     this is the end
     thank you for reading my story.

Now i wanted to compute the section in between this is the beginning and this is the end, whilst being in a while loop. So the code is

    while loop line != "":
       line = file.readline()
        if(line.find("beginning"):
            for line in range(line.find("beginning"), line.find("end"))

Now this obviously did not work but i was wondering if there is any suggestion on how i could possibly loop the lines in between those 2 sentences whilst still remaining in the overall loop?


You can use two boolean flags mark the beginning and ending.

cat sample.csv

Hello my name is jason
i am 25 and make 30,000 a year.
this is the beginning.
xxxxxxxxxxxxx
xxxxxxxxxxxxx
xxxxxxxxxxxxx
xxxxxxxxxxxxx
this is the end
thank you for reading my story.

cat test.py

BEGINNING = "this is the beginning"
ENDING = "this is the end"

with open("sample.csv", "r") as inputs:
    start_parsing, end_parsing = False, False
    for line in inputs:
        if BEGINNING in line.strip():
            start_parsing = True
            continue
        elif ENDING in line:
            end_parsing = True

        if start_parsing and not end_parsing:
            # do your work here...
            print(line.strip())

python test.py

xxxxxxxxxxxxx
xxxxxxxxxxxxx
xxxxxxxxxxxxx
xxxxxxxxxxxxx