fname input('enter the file name'tryfhand open(fnameexceptprint('file cannot be opened:'fnameexit(count for line in fhandif line startswith('subject:')count count print('there were'count'subject lines in'fnamecodethe exit function terminates the program it is function that we call that never returns now when our user (or qa teamtypes in silliness or bad file nameswe "catchthem and recover gracefullypython search py enter the file namembox txt there were subject lines in mbox txt python search py enter the file namena na boo boo file cannot be openedna na boo boo protecting the open call is good example of the proper use of try and except in python program we use the term "pythonicwhen we are doing something the "python waywe might say that the above example is the pythonic way to open file once you become more skilled in pythonyou can engage in repartee with other python programmers to decide which of two equivalent solutions to problem is "more pythonicthe goal to be "more pythoniccaptures the notion that programming is part engineering and part art we are not always interested in just making something workwe also want our solution to be elegant and to be appreciated as elegant by our peers writing files to write fileyou have to open it with mode "was second parameterfout open('output txt'' 'print(foutif the file already existsopening it in write mode clears out the old data and starts freshso be carefulif the file doesn' exista new one is created