''' files.py -- a few file-related operations, plus a first encounter with exceptions Jeff Ondich, 24 October 2006 Tianna Avery, November 2018, updated for Python 3 Read, predict the output, experiment. ''' import sys print('=============== command-line arguments ==============') if len(sys.argv) <= 1: print('Usage: {0} filename\n'.format(sys.argv[0]), file=sys.stderr) exit() file_name = sys.argv[1] print('The requested file is', file_name) print() print('=============== reading from a file ==============') try: open_file = open(file_name) except Exception as e: print('Here is the error message built into the exception:\n {0}\n'.format(e), file=sys.stderr) exit() for line in open_file: line = line.upper() print(line,) open_file.close() print() print('=============== writing to a file ==============') try: open_file = open('output.txt', 'w') except Exception as e: print('Here is the error message built into the exception:\n {0}\n'.format(e), file=sys.stderr) exit() open_file.write('the moose frolicked\n') # or, alternatively, print('the moose frolicked\n', file=open_file) open_file.write('in the meadow\n') open_file.close() print()