Changed a to w on open (Geraint's suggestion)
Explictly close files