38.6k views
5 votes
Write a script named numberlines.py. This script creates a program listing from a source program. This script should:

(a) 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
(b) The script copies the lines of text from the input file to the output file, numbering each line as it goes.
(c) The line numbers should be right-justified in 4 columns, so that the format of a line in the output file

User Mihawk
by
7.3k points

1 Answer

4 votes

Final answer:

The script 'numberlines.py' prompts the user for input and output file names, then reads from the input file, numbers each line, and writes the numbered lines to the output file with the line numbers right-justified.

Step-by-step explanation:

To write a script named numberlines.py that creates a program listing from a source program, you need to use Python's file handling capabilities. Here's a basic structure of how the script could look:

def main():
input_filename = input('Enter the input filename: ')
output_filename = input('Enter the output filename: ')

with open(input_filename, 'r') as input_file, open(output_filename, 'w') as output_file:
line_number = 1
for line in input_file:
output_line = f'{line_number:4d}: {line}'
output_file.write(output_line)
line_number += 1

if __name__ == '__main__':
main()

This script does the following: it prompts the user for the input and output file names, opens the input file for reading, the output file for writing, and writes each line from the input file to the output file, prepending it with a right-justified line number.

User Jeff Lowery
by
7.7k points