异常处理
检测文件名是否正确,然后按行读取文件,否则循环输入文件名直至正确。
def processFile(dataFile): count = 1 for item in dataFile: print('Line '+ str(count) + ':' + item.strip()) count = count + 1 while True: try: fileName = input('Input a file name to open: ') dataFile = open(fileName,'r') except IOError: print('Bad file name; try again') else: processFile(dataFile) break finally: try: dataFile.close() except NameError: print('Going around again')