def to_csv(data, field_names=None, filename='<STR_LIT>',<EOL>overwrite=True,<EOL>write_headers=True, append=False, flat=True,<EOL>primary_fields=None, sort_fields=True):
<EOL>if not overwrite and path.isfile(filename):<EOL><INDENT>raise FileExistsError('<STR_LIT>')<EOL><DEDENT>write_type = '<STR_LIT:w>' if not append else '<STR_LIT:a>'<EOL>if flat or not field_names:<EOL><INDENT>data = [flatten(datum) for datum in data]<EOL><DEDENT>if not field_names:<EOL><INDENT>field_names, data = fill_gaps(data)<EOL><DEDENT>if sort_fields:<EOL><INDENT>field_names.sort()<EOL><DEDENT>if primary_fields:<EOL><INDENT>for key in primary_fields[::-<NUM_LIT:1>]:<EOL><INDENT>field_names.insert(<NUM_LIT:0>, field_names.pop(field_names.index(key)))<EOL><DEDENT>data = sorted(data, key=lambda k: k[field_names[<NUM_LIT:0>]], reverse=True)<EOL><DEDENT>with open(filename, write_type, encoding='<STR_LIT:utf-8>') as f:<EOL><INDENT>writer = csv.DictWriter(f, fieldnames=field_names, lineterminator='<STR_LIT:\n>')<EOL>if not append or write_headers:<EOL><INDENT>writer.writeheader()<EOL><DEDENT>for datum in data:<EOL><INDENT>for key in list(datum.keys()):<EOL><INDENT>if key not in field_names:<EOL><INDENT>del datum[key]<EOL><DEDENT>elif type(datum[key]) is str:<EOL><INDENT>datum[key] = datum[key].strip()<EOL><DEDENT>datum[key] = str(datum[key])<EOL><DEDENT>writer.writerow(datum)<EOL><DEDENT><DEDENT>
DEPRECATED    Write a list of dicts to a csv file

:param data: List of dicts
:param field_names: The list column names
:param filename: The name of the file
:param overwrite: Overwrite the file if exists
:param write_headers: Write the headers to the csv file
:param append: Write new rows if the file exists
:param flat: Flatten the dictionary before saving
:param primary_fields: The first columns of the csv file
:param sort_fields: Sort the field names alphabetically
:return: None