Backport 1.7 resourcewarning fix

Fix unclosed file ResourceWarning in Python 3.