234k views
2 votes
Complete the given program that reads a file containing text. The program is required to read each line and send it to the output file, preceded by line numbers. If the input file contains Mary had a little lamb Whose fleece was white as snow. And everywhere that Mary went, The lamb was sure to go! then the program will produce an output file that contains the following content: /* 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!

User Afser
by
5.7k points

1 Answer

0 votes

Answer:

  1. texts = ""
  2. with open("text.txt") as file:
  3. texts = file.readlines()
  4. with open("output.txt", "w")as file:
  5. i = 1
  6. for s in texts:
  7. file.write("/*" + str(i) + "*/" + s)
  8. i += 1

Step-by-step explanation:

The solution code is written in Python 3.

Firstly, create a variable texts to hold the contents read from the text file. Next, open the file stream and use readlines method to read the contents from text.txt and assign it to variable texts (Line 3-4).

Next, open another file stream but for this time the file stream is used to output each row of the texts preceded by line number (Line 6 -10).

User Assassinbeast
by
5.8k points