159k views
2 votes
Write a script named numberlines.py. This script creates a program listing from a source program. This script should: Prompt the user for the names of two files. The input filename could be the name of the script itself, but be careful to use a different output filename! The script copies the lines of text from the input file to the output file, numbering each line as it goes. The line numbers should be right-justified in 4 columns, so that the format of a line in the output file looks like this example: 1> This is the first line of text

User KrekkieD
by
4.9k points

1 Answer

5 votes

Answer:

Programs can be used to read, write and append to a file

This question illustrates the read, write and append, as implemented in the following program.

The program in Python, where comments are used to explain each line is as follows;

#This initializes the line numbers to 0

num = 0

#This gets the input filename from the user

file1 = input("Input filename: ")

#This gets the output filename from the user

file2 = input("Output filename: ")

#This reads the content of file1 and appends it to file2

with open(file1, 'r') as f1, open (file2, 'w') as f2:

#This iterates through the file 1

for lines in f1:

#This calculates the line numbers

num = num + 1

#This writes into file 2, the line number and the content of the line

f2.write(num,lines)

At the end of the program, the content of the input file and the line numbers are appended to the output file.

Step-by-step explanation:

User KentH
by
5.1k points