advanced programming techniques fh none tryfh open(filenamefor line in fhprocess(lineexcept environmenterror as errprint(errfinallyif fh is not nonefh close(trywith open(filenameas fhfor line in fhprocess(lineexcept environmenterror as errprint(erra file object is context manager whose exit code always closes the file if it was opened the exit code is executed whether or not an exception occursbut in the latter casethe exception is propagated this ensures that the file gets closed and we still get the chance to handle any errorsin this case by printing message for the user in factcontext managers don' have to propagate exceptionsbut not doing so effectively hides any exceptionsand this would almost certainly be coding error all the built-in and standard library context managers propagate exceptions sometimes we need to use more than one context manager at the same time for exampletrywith open(sourceas finwith open(target" "as foutfor line in finfout write(process(line)except environmenterror as errprint(errhere we read lines from the source file and write processed versions of them to the target file using nested with statements can quickly lead to lot of indentation fortunatelythe standard library' contextlib module provides some additional support for context managersincluding the contextlib nested(function which allows two or more context managers to be handled in the same with statement rather than having to nest with statements here is replacement for the code just shownbut omitting most of the lines that are identical to beforetrywith contextlib nested(open(source)open(target" ")as finfout)for line in fin