使用 Python3 将 .txt 文件中的文本换行?

Wrap text in .txt file with Python3?

你好,我解释一下我的问题,我尝试将我的文本换行成几行,在终端中工作的方法很酷,我有一个换行,但问题是在我的文本文件中写入,无法换行文本,我只好把函数转了个遍,我没成功,那我post初始方法如果有人有想法我是taker

phrase = "bla bla bla ceci est une phrase beaucoup trop longue pour ce que je doit réellement dire, en fait je peux même dire qu'elle ne sert a rien, mais du coup je doit quand même la tester"

# lim=40
# line = []
# with open("test.txt", "w") as fiche:
#     for s in phrase.split("\n"):
#         if s == "":
#             break
#         word=0 
#         for d in s.split():
#             if word + len(d) + 1 <= lim:
#                 line.append(d)
#                 word += len(d) + 1 
#             else:
#                 print(" ".join(line))
#                 fiche.write(" ".join(line))

#                 line = [d] 
#                 word = len(d)
#         if (len(line)):
#             print(" ".join(line))
#             fiche.write(" ".join(line))

attempt n°2 :

my_wrap = textwrap.TextWrapper(width = 40)
wrap_list = my_wrap.wrap(text=phrase)

with open("test.txt", "w") as fiche:
    for line in wrap_list:
        print(line)
        fiche.write(" ".join(line))

您需要在两行之间添加新行 \n

with open("test.txt", "w") as fiche:
    for line in wrap_list:
        print(line)
        fiche.write(f'\n{" ".join(line)}')

如果您不希望字母之间有空格,请删除 " ".join

with open("test.txt", "w") as fiche:
    for line in wrap_list:
        print(line)
        fiche.write(f'\n{line}')

或者直接使用writelines

with open("test.txt", "w") as fiche:
    fiche.writelines('\n'.join(wrap_list))

您可以使用自动为您放置换行符的textwrap.fill,您可以直接将其写入文件:

with open("test.txt", "w") as fiche:
    fiche.write(my_wrap.fill(phrase))

test.txt的内容为:

bla bla bla ceci est une phrase beaucoup
trop longue pour ce que je doit
réellement dire, en fait je peux même
dire qu'elle ne sert a rien, mais du
coup je doit quand même la tester