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.