首页 > 解决方案 > How would I create a new line in a text document after the nth word?

问题描述

I am working on a project in which I have to list a whole lot of things out in this format

[*] This is the first object
[*] This is the second object
[*] When the object gets too long, I need to move it to the next line
    to look like this. 

I created a .py file and a .txt file. I would input the list objects into the .py file and it would properly format it into the text file. I tried something like this:

text = input('> ')
with open('list.txt', 'a') as f:
    f.write(f'[*] {t}\n')

But I can't seem to move it to the next line. Around the 15th word, is when I want to go to a new line.

How can I achieve this?

标签: pythonfiletext

解决方案


Print the bullet first. Then split the text into a list of words, and print each one in a loop. Inside the loop, keep track of how many words have been printed on the current line, and of you reach 15, print a newline and reset the count to zero.

with open('list.txt', 'a') as f:
    # print the bullet
    f.write('[*]')

    wordcount = 0

    # loop over each word in the text
    for word in text.split():
        f.write(f' {word}')
        wordcount += 1

        # if this line has 15 words, start a new line
        if wordcount == 15:
            f.write('\n   ')
            wordcount = 0

    # finally write a newline
    f.write('\n')

推荐阅读