0

I'm fairly new to programming and Python, other than really simple logic stuff. Anyway, I'm trying to go through a txt file and get all the lines below a certain word, until there's a space. But then I would like python to continue on to see if the word appears further on and also collect those lines.

So, the text file I'm going through looks something like this (but a LOT bigger):

Some lines of text:

More Text

[Topic 1]

 1 - Blabla   Blabla   Blabla

 2- Blabla   Blabla   Blabla

[Topic 2]

1 - Blabla   Blabla   Blabla

2- Blabla   Blabla   Blabla

Some more text I don't need..."

What I would like to do is get all the lines below all Topics... so, whenever the word "Topic" appears, I would like to get all lines below that one, until a space appears. Now, after reading some posts, I've tried this (I'm using Python 3), but all I get are the lines below Topic 1: (I am writing it out to another file as output right now)

def get_topics(in_f, out_f, end):
        with open(in_f) as f, open(out_f,"a") as out:
        for line in f:
                if '[Topic' in line:
                    line=line.strip()
                    out.write(line)
                    for line in f:
                        if line.strip()==end:
                            out.write(line)
                            return
                        out.write(line)                   
get_topics("Ex_test.txt","test_topics.txt","") 

I think I should get it to loop somehow, because I am only getting the first iteration, and should be a pretty straightforward fix.

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
JRM
  • 17
  • 1

0 Answers0