Made code Python 3 compatible by closing files