如何将文本文件重新格式化为具有给定行宽的新文本文件

时间:2013-05-11 14:06:53

标签: python-3.x

如何将文本文件重新格式化为具有给定线宽的新文件?

例如:

示例文件input.txt

Your program should store a single row of the triangle and calculate each subsequent row by adding a value to the values
immediately above it and to its left. The values on each line must be space-separated.

示例文件output.txt

Your program should store a single row
of the triangle and calculate each
subsequent row by adding a value to the
values immediately above it and to its
left. The values on each line must be
space-separated.

示例控制台I / O:

Enter the input filename:
input.txt
Enter the output filename:
output.txt
Enter the line width:
40

1 个答案:

答案 0 :(得分:1)

使用textwrap.fill

import textwrap

text = '''Your program should store a single row of the triangle and calculate each subsequent row by adding a value to the values immediately above it and to its left. The values on each line must be space-separated.'''

print(textwrap.fill(text, 40))

产量

Your program should store a single row
of the triangle and calculate each
subsequent row by adding a value to the
values immediately above it and to its
left. The values on each line must be
space-separated.