Create a file with a 20 lines of text and name it "lines.txt". Write a program to read this a file "lines.txt" and write the text to a new file, "numbered_lines.txt", that will also have line numbers at the beginning of each line.

Respuesta :

Answer:

I am writing a Python program:

read_file = open("lines.txt", 'r')  #opens file in read mode

#read_file is a file object

lineNo = 1  #assigns line number to each line

write_file = open("numbered_lines.txt", 'w')# opens file in write mode

#write_file is a file object

for i in read_file:  # loop on read file

   write_file.write(str(lineNo) + " " + i)

#writes line number on start of each line in write file  

   lineNo += 1  increments line number

read_file.close()  # closes file to read

write_file.close() # closes file to write on

Explanation:    

This program first opens the file name lines.txt to read the contents of the file using open() function. Then the new file numbered_lines.txt is opened in write mode to write the contents on it. Then the for loop moves through each line of lines.txt and adds the line numbers to each line of the numbered_lines.txt .The line number lineNo increments by 1 at each iteration so that each line of the file gets a number from 1 to 20. At the end both the files are closed using close() function. The screen shots of program and both the files is attached.

Ver imagen mahamnasir
Ver imagen mahamnasir
Ver imagen mahamnasir