Read Up Until a Point Python

user1985351 picture user1985351 · Apr 12, 2013 · Viewed 17.9k times · Source

I have a text file full of data that starts with

#Name
#main

then it's followed by lots of numbers and then the file ends with

#extra
!side

So here's a small snippet

#Name
#main
60258960
33031674
72302403
#extra
!side

I want to read only the numbers. But here's the kick, I want them to each be their own individual string.

So I know how to read starting after the headers with

read=f.readlines()[3:]

But I'm stumped on everything else. Any suggestions?

Answer

Keith John Hutchison picture Keith John Hutchison · Apr 12, 2013

Read line by line. Use #main as a flag to start processing. Use #extra as a flag to stop processing.

start = '#main'
end = '#extra'
numbers = []
file_handler = open('read_up_to_a_point.txt')
started = False
for line in file_handler:
    if end in line:
        started = False       
    if started:
        numbers.append(line.strip())
    if start in line:
        started = True
file_handler.close()
print numbers

sample output

python read_up_to_a_point.py ['60258960', '33031674', '72302403']