Home > database >  Read a block in a large text file
Read a block in a large text file

Time:05-03

I have a pretty large text file and I am trying to read a block of lines based on a start and end keyword. Below is the text file:

.Threshold = 0.000100
.Threshold = 0.000100
.Threshold = 0.000100
.ShapesOf = 0.11
.Viades = 0.000000

.Connect U4 12345
test1
test2
test3
.EndC

.Connect U5 123
test1
test2
test3
.EndC

.Connect U6 12576
test1
test2
test3
.EndC

.Connect U7 54367
test1
test2
test3
.EndC

.Connect U8 54367
test1
test2
test3
.EndC

I am trying to do it using break and continue and below is the script:

with open("test.txt") as ff:
    for line in ff:
        if line.startswith('.Connect U5 '):
            continue
        if line == ".EndC":
            break
        print(line)

My search keyword is .Connect U5. I want everything in between .Connect U5 and the very next .EndC. The code is returning me the entire file. Any help?

CodePudding user response:

You compare lines with "\n" at the ends. You also continue, when you find the start marker.

beginOutput = false
with open("test.txt") as ff:
    for line in ff:
        if line.startswith('.Connect U5'):
            beginOutput = true

        if not beginOutput:
            continue

        if line.strip() == ".EndC":
            break

        print(line)

Note the strip(). It's not the best solution, because it will strip all the lines in your file. Try to strip() only the lines which start with .EndC marker

  • Related