I think you should simply open the file at a higher level and pass it in as ``writer``; no reason to open/close it in this function at all.