In: Computer Science
In Python please: Number the Lines in a File: Create a program that adds line numbers to a file. The name of the input file will be read from the user, as will the name of the new file that your program will create. Each line in the output file should begin with the line number, followed by a colon and a space, followed by the line from the input file.
Program code to copy:-
#This program adds line numbers to a input file and
#stores the content of file with line number into another
file.
#Name of both input and output file entered by the user.
#Prompt the user to enter input file name
inputFileName = input('Enter the input file name: ')
#Prompt the user to enter output file name
outputFileName = input('Enter the input file name: ')
#Open the file for reading
fin = open(inputFileName, "r")
#Open the file for writing
fout = open(outputFileName, "w")
lineNo = 1 #Used to keep track of line number
#Loop read the content of input file line by line and
#store each line into variable 'line' till end of input file
for line in fin:
#Writing line with line number into output file
fout.write(str(lineNo) + ": " + line)
lineNo = lineNo + 1
#Closing both input and output file
fin.close()
fout.close()
Screenshot of Program Code:-
Screenshot of program output:-
Screenshot of input file:-
Screenshot of output file:-
Note:- Before executing above program code you need to create a input file and store it into current working folder.