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
#9
I can't test it cause I am not at home and can't install Python here.

with open(file_name, 'r') as f:
    book = f.readlines()

while book:                        
    line = book.pop(0)
     
    if "CHAPTER" in line and book.pop(0) == '\n':
        for title in chapters_names_list: # your lies of chapter names here
            with open("{}.txt".format(chapters_names_list), 'w') as f:
                try:
                    while True:
                        line = pop(0)
                        if 'CHAPTER' in line:
                            break
                        else:
                            f.write(line)
                except IndexError:
                    pass
While this might work but you should look at @snipsat code snipped. It seems to be more clear than this. If you decide to use the code above it will be empty lines in the text. One above the title and at the end of the chapter a few more.

And I should not write a full working code but... I can't explain what is in my head very well. My English is not so good as I need for this.
"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-17-2017, 08:06 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  dictionary output to text file (beginner) Delg_Dankil 2 1,221 Jul-12-2023, 11:45 AM
Last Post: deanhystad
  Output File ? Kessie1971 11 2,073 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,602 Feb-05-2021, 10:49 AM
Last Post: buran
  Read text file, process data and print specific output Happythankyoumoreplease 3 2,940 Feb-20-2020, 12:19 PM
Last Post: jefsummers
  parse text, save individual chapters into text files isniffbooks 3 3,832 Nov-07-2019, 12:04 AM
Last Post: isniffbooks
  Convert text from an image to a text file Evil_Patrick 5 4,326 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,496 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,482 Dec-11-2018, 02:19 PM
Last Post: ichabod801
  Multiple XML file covert to CSV output file krish143 1 3,367 Jul-27-2018, 06:55 PM
Last Post: ichabod801
  How to get output in a file? BananaRekt 3 3,183 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