This looks really ugly. Are you trying to generate a CSV here? There is csv.writer for that.