Shu Ping
Shu Ping

Reputation: 1

How do i reformat a text file to a new one with a given line width

How do I reformat a text file to a new one with a given line width?

For example:

Sample File 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.

Sample File 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.

Sample console I/O:

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

Upvotes: 0

Views: 150

Answers (1)

unutbu
unutbu

Reputation: 879919

Use 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))

yields

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.

Upvotes: 1

Related Questions