Simplify the code.

Avoid too much nesting of code.
Open file using the with keyword, avoid calling f.close() explicitly.