Avoid resource leaks with open files.

As a bonus, since we are changing one place where a file is written to and
the semantics happen to be different with different Python implementations
(e.g., CPython and Pypy), we gain one step forward to making coursera-dl
work under Pypy.

For an illustration of this later point, see the section "Known differences
that are not going to be fixed" in the following document:

    http://pypy.org/compat.html

Passes our unittests, some manual testing and real-world uses too.
Add another avoidance point of resource leaks with open files.