Python: Extract chapter from long txt (or delete all other chapters)
Question: My problem is: I have several long txt files with many chapters of which I
want to extract one. The text within these chapters differs between files.

Identification should be done using the title of the chapter and the title of
the next chapter, which are the same for all files. These identification-
titles are in the file more than once, but I want to only use their first
occurrence...

Thus the logic is something like:

delete text; identification title (first occurrence) "start"; keep title and
text; identification title (first occurrence) "end"; delete text

The goal is a program, which will automatically open all files and edit them
in the stated way.

Thanks in advance!


Answer: I found a (somehow long) answer, which does only delete the first part of the
text (that means the chapter is not extracted but at least it is at the top,
which is sufficient for me)... maybe someone'll have the same problem:

    
    
    import os  
    for file in os.listdir('.'):
        if file == "delete_first_part.py":
            pass
        elif os.path.isfile(file):
            # open the file, delete all lines before "word to begin", write rest to file
            f = open(file,"r+")
            lines = reversed(f.readlines())
    
            f.seek(0)
            strings = ("Word to Begin")
            for line in lines:
                if any(s in line for s in strings):
                    f.write(line)
                    f.truncate()
                    print file
                    break
                else:
                    f.write(line)
    
            f.close()
    
            f = open(file,"r+")
            lines = reversed(f.readlines())
    
            f.seek(0)
    
            for line in lines:
                f.write(line)
    
            f.close()
    

I read the file from the end, search for my "word to begin", truncate the rest
of the text and break the loop. Then write to file, open it again and read
from the end -> the end up with the text in the "right" direction.

