finally clause is the most generalsince it allows you to provide general exit actions for any type of exceptionsmyfile open(filename' 'tryprocess myfile finallymyfile close(in recent python releasesthoughthe with statement provides more concise alternative for some specific objects and exit actionsincluding closing fileswith open(filename' 'as myfileprocess myfileauto-closed on statement exit this statement relies on the file object' context managercode automatically run both on statement entry and on statement exit regardless of exception behavior because the file object' exit code closes the file automaticallythis guarantees file closure whether an exception occurs during the statement or not the with statement is notably shorter ( linesthan the try/finally alternativebut it' also less general--with applies only to objects that support the context manager protocolwhereas try/finally allows arbitrary exit actions for arbitrary exception contexts while some other object types have context managerstoo ( thread locks)with is limited in scope in factif you want to remember just one exit actions optiontry/finally is the most inclusive stillwith yields less code for files that must be closed and can serve well in such specific roles it can even save line of code when no exceptions are expected (albeit at the expense of further nesting and indenting file processing logic)myfile open(filename' 'process myfile myfile close(traditional form with open(filenameas myfileprocess myfile context manager form in python and laterthis statement can also specify multiple ( nestedcontext managers--any number of context manager items may be separated by commasand multiple items work the same as nested with statements in general termsthe and later codewith (as ab(as bstatements runs the same as the followingwhich works in and with (as awith (as bstatements file and directory tools