more direct closure inside loops to avoid taxing system resourcesdue to differing garbage collectors even more usefullythe following automatically closes the output file on statement exitto ensure that any buffered text is transferred to disk immediatelywith open('script py'as finopen('upper py'' 'as foutfor line in finfout write(line upper()print(open('upper py'read()import sys print(sys pathx print( * in both caseswe can instead simply open files in individual statements and close after processing if neededand in some scripts we probably should--there' no point in using statements that catch an exception if it means your program is out of business anyhowfin open('script py'fout open('upper py'' 'for line in finfout write(line upper()same effect as preceding codeauto close howeverin cases where programs must continue after exceptionsthe with forms also implicitly catch exceptionsand thereby also avoid try/finally in cases where close is required the equivalent without with is more explicitbut requires noticeably more codefin open('script py'fout open('upper py'' 'tryfor line in finfout write(line upper()finallyfin close(fout close(same effect but explicit close on error on the other handthe try/finally is single tool that applies to all finalization caseswhereas the with adds second tool that can be more concisebut applies to only certain objects typesand doubles the required knowledge base of programmers as usualyou'll have to weigh the tradeoffs for yourself summary in this we took more detailed look at exception processing by exploring the statements related to exceptions in pythontry to catch themraise to trigger themassert to raise them conditionallyand with to wrap code blocks in context managers that specify entry and exit actions summary