Home > OS >  How to split text file into small multiple files at specific text or line?
How to split text file into small multiple files at specific text or line?

Time:06-02

I have txt file of book which have word "-THE END-" at every chapter. I wanted to split each chapter into different file like-

Chapter001.txt
Chapter002.txt
Chapter003.txt
.
.
.
ChapterNNN.txt

I have written following code in python3.

groups = open('input.txt').read()
groups_divided = groups.split('-THE END-\n')
temp = group.split('\n')

I want now it to split it into different files and give them name "Chapter". Also I am not getting how to split and create files and ensure that it is covered all queries.

Also please tell me if there is any simple method to do it via any software.

CodePudding user response:

You could do it by processing the input text file a line at a time instead of reading the whole thing into memory first by simply iterating over and accumulating each line in it until an "end of chapter" line is encountered:

with open('input.txt') as inp:
    n = 1
    chapter = []
    for line in inp:
        if line != '-THE END-\n':
            chapter.append(line)
        else:
            filename = f'Chapter{n:03d}.txt'
            with open(filename, 'w') as outp:
                outp.writelines(chapter)
            n  = 1
            chapter = []

CodePudding user response:

n = 0
for chapter in groups_divided:
    with open(f'chapter{n}.txt', 'w') as file: 
       file.write(chapter)
       n  = 1
  • Related