I think you need to close 'writer'. How about calling 'conn.disconnect()' in 'finally' clause.