# Program to print file contents with line number prepended to each line # This one writes to a file with the same base name but with ".lst" appended # # Matt Bishop, ECS 10, Fall 2012 # def main(): # get file name try: iname = input("Please enter the name of the file to print: ") except EOFError: return except: print("Could not read what you typed") return # get the listing file name # replace extension with ".lst" or append ".lst" to file name pos = iname.rfind(".") if pos == -1: oname = iname + ".lst" else: oname = iname[0:pos] + ".lst" # # open input, output files # try: infile = open(iname, 'r') except IOError: print("Error opening file", iname, "for reading") return except: print("Unknown error") return try: outfile = open(oname, 'w') except IOError: print("Error opening file", oname, "for writing") return except: print("Unknown error") return # # line by line, adding line numbers as we go # # initialize line counter lineno = 1; # for each line in the file ... for line in infile: # print the line number, then the line print("%6d. " % lineno, line, file=outfile, end='') lineno = lineno + 1 # all done! infile.close() outfile.close() main();