# Author: James Tam # Version: March 28, 2018 # # Learning objectives: # * File input error handling using exceptions: empty file name, # empty file fileOK = False while (fileOK == False): filename = input("Enter name of file: ") # JT: the following two IF-constructs check for the same # thing both are included to illustrate two equally correct # ways of checking. if (filename == ""): print("File name cannot be blank") # Equally valid alternative # if (len(filename) == 0): # print("File name cannot be blank") # If name not blank, try to open file else: try: inputFile = open(filename,"r") line = inputFile.readline() # Tried to read line from newly opened file, # if string is empty then the file must be empty if (len(line) == 0): print("File %s is empty" %filename) else: while (len(line) > 0): print(line) line = inputFile.readline() fileOK = True inputFile.close() except IOError: print("Error cannot open %s" %filename)