如何在python中使用textwrapper进行文件操作

如何在python中使用textwrapper进行文件操作,python,Python,我正在尝试编写一个输出文件,将每行字符数限制为60个字符。我设法读入文本文件,使其每行60个字符,但它添加了不在同一行的单词。例如,读入文件是 Albuquerque is my turkey and he's feathered and he's fine, And he wobbles and he gobbles and he's absolutely mine He's the best pet you can get yet better than a dog or cat, He'

我正在尝试编写一个输出文件,将每行字符数限制为60个字符。我设法读入文本文件,使其每行60个字符,但它添加了不在同一行的单词。例如,读入文件是

Albuquerque is my turkey and he's feathered and he's fine, And he
wobbles and he gobbles and he's
absolutely mine

He's the best pet you can get yet better than
a dog or cat, He's my albuquerque turkey and i'm awfully proud of that
在使用文本包装器方法之后

Albuquerque is my turkey and he's feathered and he's fine,
And he wobbles and he gobbles and he's absolutely mine  He's

the best pet you can get yet better than a dog or cat, He's
my albuquerque turkey and i'm awfully proud of that
应该是这样

Albuquerque is my turkey and he’s feathered and he’s fine,
And he wobbles and he gobbles and he’s absolutely mine

He’s the best pet you can get yet, better than a dog or cat,
He’s my albuquerque turkey and i’m awfully proud of that
如何调整文本包装器方法以适应句子

def adjust_linelength():
    with open("essay_neb.txt") as file:
        text = file.read().strip()
    with open("essay_final.txt", 'w') as file:
        file.write(textwrap.fill(text, width=60))
据报道,

text wrap.fill(文本[,宽度[,…])

将单个段落包装为文本,并返回包含包装段落的单个字符串

如果您先将文本分成段落,然后在每个段落上运行textwrapper,它应该可以工作。

根据

text wrap.fill(文本[,宽度[,…])

将单个段落包装为文本,并返回包含包装段落的单个字符串

如果您先将文本分解为段落,然后在每个段落上运行textwrapper,它应该可以工作