1 #coding:utf-8 # using Windows system, first line ' #!/usr/bin/env Pyton ' useless, all changed to ' # Coding:utf-8 '
2 3 'readtextfile.py--Read and display text file'4 5 #get filename6fname = Raw_input ('Enter FileName:')7 Print8 9 #attempt to open file for readingTen Try: OneFobj = open (fname,'R') # Try to open fname A exceptIOError, E:#The detailed cause of the captured IOError error is placed in Object E, and then the except code block that runs the exception (can also be written as ' except IOError as e: ') - Print "* * * File Open error:", E # print exception information - Else: # If the try has no errors, execute the Else statement the #Display contents to the screen - forEachlineinchFobj: - PrintEachline, # Comma is to resist the print statement automatically generated line terminator (FName inside itself has a line terminator, if you do not add a comma, there will be a blank line between the printed content) -Fobj.close ()
Keywords related to python exceptions:
Keyword keyword description
Raise throw/Throw exception
Try/except catching exceptions and handling
Pass ignores exceptions
As definition exception instance (except IOError as E)
Finally code that executes regardless of whether an exception occurs
Else If the statement in the try does not throw an exception, the statement in the else is executed
First encounter with Try-except (Core Python programming 2nd Edition 3.6)