Python如果行超过50个字符,则插入新行

Den*_*1al 0 python string newline line python-2.7

我一直试图弄清楚Python上的一个问题让我疯狂了几个星期......我有一个文本文件,文本数量不错.有些行有超过50个字符,这对我来说是一个问题,因为它必须与文本框对齐.

我的问题是:如果文本文件中的一行超过50个字符(包括空格),如何设置插入新行(\n)?

提前致谢.

Ste*_*nes 8

这里有一个图书馆.请尝试以下方法:

import textwrap

wrapped = textwrap.fill(YourText, 50)
Run Code Online (Sandbox Code Playgroud)


ins*_*get 5

这应该可以解决问题

with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
  for line in infile:
    if len(line) > 50:
      outfile.write('\n'.join(line[i:i+50] for i in xrange(0,len(line), 50)))
    else:
      outfile.write(line)
Run Code Online (Sandbox Code Playgroud)