Instead of this:
FILE = open(f)
do_something(FILE)
FILE.close()
it\'s better to use this:
with open(f) as FILE:
do_some
While all of the other answers are excellent, and preferable, note that the with expression may be any expression, so you can do:
with (open(file) if file is not None else None) as FILE:
pass
Note that if the else clause were evaluated, to yield None this would result in an exception, because NoneType does not support the appropriate operations to be used as a context manager.