Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@squarepegsys
Created August 4, 2021 21:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save squarepegsys/54c06e8ed1f730b5d515f248bbf9a768 to your computer and use it in GitHub Desktop.
Save squarepegsys/54c06e8ed1f730b5d515f248bbf9a768 to your computer and use it in GitHub Desktop.
Generic pydemic object to CSV export
# assumptions:
# mappings is a list of pydentic objects extending BaseModel - https://pydantic-docs.helpmanual.io
# filename is the filename you want to export to
import csv
from pathlib import Path
def out_mapping(filename: str, mappings: List):
out_csv = Path(filename)
fields = list(mappings[0].__fields_set__)
with out_csv.open("w") as out_fp:
writer = csv.DictWriter(out_fp, fieldnames=fields)
[writer.writerow(x.dict()) for x in mappings]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment