''' 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(f'Usage: {sys.argv[0]} filename\n', 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(f'Here is the error message built into the exception:\n {e}\n', file=sys.stderr) exit() for line in open_file: line = line.upper() print(line, end='') open_file.close() print() print('============== reading from a file using the "with" statement ==============') print(' (this ensures that your file will get closed automatically)') with open(file_name) as open_file: for line in open_file: line = line.upper() print(line, end='') print() print('=============== writing to a file named output1.txt ==============') try: open_file = open('output1.txt', 'w') except Exception as e: print(f'Here is the error message built into the exception:\n {e}\n', file=sys.stderr) exit() print('the moose frolicked', file=open_file) print('in the meadow', file=open_file) # or, alternatively: # open_file.write('the moose frolicked\n') # open_file.write('in the meadow\n') open_file.close() print() print('=============== writing to a file named output2.txt using "with" ==============') print(' (this is a more modern and robust idiom for opening and using files)') with open('output2.txt', 'w') as open_file: print('the moose frolicked', file=open_file) print('in the meadow', file=open_file) print()