-5

I have a .txt file called book.txt that I want to divide into multiple .txt files (one per chapter). I would like to end up having .txt files whose names refer to those chapters. For example, if book.txt has 20 chapters, I would end up with 1.txt, 2.txt, etc.

This is what I have so far:

import re
book = #I don't know how to import the book.txt file here

chapters = re.split("Chapter ", book, flags = re.IGNORECASE)
for chapter in chapters:
    #Code to write a new .txt file with each element from the list I created using the number after 'Chapter' as the name for the .txt file.

As you can see, I'm stuck at importing my book.txt file and at creating the new txt files. I'm fairly new to Python, so let me know if you need additional info.

Me All
  • 269
  • 1
  • 5
  • 17
  • 5
    Have you done any research? Reading text files is a popular topic, there are plenty of resources available. – AMC Feb 09 '20 at 22:37
  • Does this answer your question? [How to read a large file line by line](https://stackoverflow.com/questions/8009882/how-to-read-a-large-file-line-by-line). And https://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file – Tomerikoo Feb 09 '20 at 22:40
  • So you want to `open` a file? – MisterMiyagi Feb 09 '20 at 22:42
  • Does this help https://www.w3schools.com/python/python_file_open.asp – Chris Feb 09 '20 at 22:43
  • it's not just about opening a file, it's about creating multiple files and using the number of chapters as file names... – Me All Feb 09 '20 at 22:45
  • https://www.w3schools.com/python/python_file_write.asp – Chris Feb 09 '20 at 23:02

1 Answers1

0

This Works for me:

import re
book = open("book.txt", "r") #Here we open the book, in this case it is called book.txt
book = str(book.read()) #this is now assigning book the value of book.txt, not just the location
chapters = re.split("Chapter ", book, flags = re.IGNORECASE) #Finds all the chapter markers in the book and makes a list of all the chapters
chapters.pop(0) # Removes the first item in list as this is ""
for i in range(1, len(chapters)+1): #Loops for the number of chapters in the book, starting at chapter 1
    writeBook = open("{}.txt".format(i), "w+") #Opens a book with the name of i, if it does not exist, it creates one
    writeBook.write(chapters[i-1]) #Overwrites what is written in the book with the same chapter in the list
    writeBook.close() #Finally, it closes the text file

Please Note: this will not work with a book that has a prologue as it will just remove them from the list of chapters.

Chris
  • 362
  • 3
  • 20