Remove duplicated code
Remove duplicated code

Factor the common logic into a separate function and use that. There is
a difference in functionality: if an exception is raised inside the
functions, new code will always correctly close the file.

release-engineering/productmd,release-engineering/productmd,lubomir/productmd,lubomir/productmd