Python Forum
Parse text from a .txt file and save multiple output .txt
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Parse text from a .txt file and save multiple output .txt
#4
Hello! You do not need the table of contents. You can get the chapter name and use it.
Here is example script which loads the file lines into a list. Read each line and looks for 'CHAPTER' in the line. Then if the next line is empty, it gets the next line and this is the file name. Writes to the file until two new lines are reached.

while book:                        
    line = book.pop(0)
    
    if "CHAPTER" in line and book.pop(0) == '\n':
        chapter = line.strip()
        title = book.pop(0).strip("\n\r\ .")
        
        with open("{} - {}.txt".format(chapter,title), 'w') as f:
            print('Writing: "{} - {}.txt"'.format(chapter,title))
            
            new_lines = 0
            try:
                while new_lines < 3:
                    row = book.pop(0)
                    if row == '\n':
                        f.write(row)
                        new_lines += 1
               else:
                   f.write(row)
                   new_lines = 0
            except IndexError:
                pass
Hm! The indentation could be messy.  Dodgy
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Messages In This Thread
RE: Parse text from a .txt file and save multiple output .txt - by wavic - Mar-15-2017, 10:41 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  dictionary output to text file (beginner) Delg_Dankil 2 1,305 Jul-12-2023, 11:45 AM
Last Post: deanhystad
  Output File ? Kessie1971 11 2,272 May-11-2023, 08:31 AM
Last Post: buran
Bug [for a h/w project] How to save and get back dictionary in a .json file in TinyDB. adithya_like_py 4 3,667 Feb-05-2021, 10:49 AM
Last Post: buran
  Read text file, process data and print specific output Happythankyoumoreplease 3 2,994 Feb-20-2020, 12:19 PM
Last Post: jefsummers
  parse text, save individual chapters into text files isniffbooks 3 3,876 Nov-07-2019, 12:04 AM
Last Post: isniffbooks
  Convert text from an image to a text file Evil_Patrick 5 4,402 Jul-30-2019, 07:57 PM
Last Post: DeaD_EyE
  Using Pandas to save csv file into mysql database with for loop kirito85 4 3,570 Feb-05-2019, 01:13 AM
Last Post: kirito85
  reading text file and writing to an output file precedded by line numbers kannan 7 10,598 Dec-11-2018, 02:19 PM
Last Post: ichabod801
  Multiple XML file covert to CSV output file krish143 1 3,411 Jul-27-2018, 06:55 PM
Last Post: ichabod801
  How to get output in a file? BananaRekt 3 3,257 May-06-2018, 06:04 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020