Skip to content

Python - CSV

Examples

Write dict to a csv:

import csv

data = [
    {"head1": "text", "head2": "text"},
    {"head1": "text", "head2": "text"}
]

with open("file.csv", "w", encoding="UTF8", newline="") as of:
    headers = list(data[0].keys())
    writer = csv.DictWriter(of, fieldnames=headers, delimiter=";")
    writer.writeheader()
    writer.writerows(data)

Write multiline raw:

import csv
data = ("1", "2\n3", "4")

with open("file.csv", "w", encoding="UTF8", newline="") as of:
    writer = csv.DictWriter(of, dialect=csv.excel, delimiter=";")
    writer.writerow(data)
Back to top