Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. (linenumbers.py) Write a program that asks the user for the name of the file.

ID: 675348 • Letter: 1

Question

1. (linenumbers.py) Write a program that asks the user for the name of the file. The program should write the contents of this input file to an output file. In the output file, each line should be preceded with a line number followed by a colon. The output file will have the same name as the input filename, preceded by “ln” (for linenumbers). Be sure to use Try/except to catch all exceptions.

For example, when prompted, if the user specifies “sampleprogram.py” and that file contains:

#Jackie Horton

#CS21

#Sample program

print('This is a sample program')

print('Do you remember when this seemed hard?')

print('Python is Cool!')

Your program will produce the file named ln_sampleprogram.py and it will contain:

1: #Jackie Horton

2: #CS21

3: #Sample program

4:

5: print('This is a sample program')

6: print('Do you remember when this seemed hard?')

7: print('Python is Cool!')

PLEASE ANSWER THIS IN PYTHON!!!!!

Explanation / Answer

Complete Program:

File: linenumbers.py

Input file: sampleprogram.py

Output file: ln_sampleprogram.py

CODE TO COPY:

try:
    infile = open("sampleprogram.py", "r")
    outfile = open("ln_sampleprogram.py", "w")
    count = 0

    for line in infile:
        line = line.rstrip()
        count = count + 1
        outfile.write(str(count) + ": " + line + " ")

    infile.close()
    outfile.close()
except IOError:
    print("File not found!")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise