115k views
5 votes
Write a program that reads a file containing some text, and sends each line, preceded by line numbers, to an output file.

For example, if the input file is
Mary had a little lamb Whose fleece was white as snow.
And everywhere that Mary went,
The lamb was sure to go!
the program produces an output file with the following contents:
/* 1 */ Mary had a little lamb
/* 2 */ Whose fleece was white as snow.
/* 3 */ And everywhere that Mary went,
/* 4 */ The lamb was sure to go!
The starter code provides you with the names of the input and output files retrieved from prompting the user.

1 Answer

7 votes

Final answer:

To write a program that reads a file containing text and sends each line, preceded by line numbers, to an output file, you can use a programming language such as Python.

Step-by-step explanation:

To write a program that reads a file containing text and sends each line, preceded by line numbers, to an output file, you can use a programming language such as Python. Here is an example of Python code that accomplishes this:

input_file = 'input.txt'
output_file = 'output.txt'

# Open the input file
with open(input_file, 'r') as file:
lines = file.readlines()

# Open the output file
with open(output_file, 'w') as file:
for i, line in enumerate(lines):
# Write the line number and the line content to the output file
file.write('/* {} */ {}
'.format(i+1, line.strip()))

This code reads the lines from the input file, then iterates over them using the enumerate function to get both the line number and the line content. It then writes the formatted line to the output file.

User Timothy Randall
by
7.8k points