'How can I read through a file and insert a new line when there are 25 words in Python

Initially I was going to create a list of the words in the line with 25 words or more and then iterate through that as well. This is what I have so far:

text = 'text.txt'
handle= open(text)
line_count=0
for line in handle:
    line_count = line_count + 1
    word_count = 0
    split_line = line.split()
    for word in split_line:
        word_count = word_count + 1
        if count == 25:
    print(line)

I want to be able to create a new line so that the text doesn't exceed the borders of the screen.



Solution 1:[1]

Let's not re-invent the wheel, there is a library that allows you to wrap text based on lenght, textwrap. This is an example:

import textwrap
lenght = 200
with open("test.txt", "r") as file:  # Open a file with read permissions.
    content = file.read()  # Read the content of the file

wrapper = textwrap.TextWrapper(width=lenght)  # Define the wrapper
wrapped_text = wrapper.wrap(text=content)  # Wrap your text, this creates a List

with open("test_result.txt", "w") as file2:  # Open a file with write permissions.
    file2.write("\n".join(wrapped_text))  # Write the wrapped list into the file.

I used two different files because I feel it'll be easier for you if you can see the difference between the two files after the proccesing.

Bonus: Since we used with we don't have to close the files, they get closed automatically. Context managers are always something good to learn, take a look: https://book.pythontips.com/en/latest/context_managers.html

Solution 2:[2]

This is the solution to my understanding of what you want to do!

so at first, there was an indentation problem in your code in the last line where you do print(line) Also as I thought you want to print every 25 words as one line in your output, Right? to do that I defined new_line that holds new 25 words each time and prints them to the output

let me know if you need sth else?

text = 'text.txt'
handle= open(text)
line_count=0
new_line = " "
for line in handle:
    line_count = line_count + 1
    word_count = 0
    split_line = line.split()
    for word in split_line:
        word_count = word_count + 1
        new_line += word + " "
        if word_count == 25:
            word_count = 0
            print(new_line)
            new_line = " "

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2