Created
February 24, 2020 06:37
-
-
Save junetech/9cf0a208ae5477080c471f05223493f8 to your computer and use it in GitHub Desktop.
Create and write to csv file using DictWriter in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Any, Dict, List | |
def create_write_csv(formatted_list: List[Dict[str, Any]], | |
fieldnames: List[str], | |
filepath: str, | |
encoding: str): | |
"""row 정보를 가진 dictionary의 list를 받아 filepath에 csv로 저장 | |
Arguments: | |
formatted_list {List[Dict[str, str]]} -- column head를 key, 값을 value로 하는 dictionary의 list | |
filepath {str} -- file의 절대/상대 경로 | |
fieldnames {List[str]} -- formatted_list의 key와 일치한다고 가정 | |
encoding {str} -- encoding | |
""" | |
import os, csv | |
if not os.path.exists(filepath): | |
os.makedirs(filepath) | |
with open(filepath, 'w', newline="", encoding=encoding) as _file: | |
file_writer = csv.DictWriter(_file, fieldnames=fieldnames) | |
file_writer.writeheader() | |
for row in formatted_list: | |
file_writer.writerow(row) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment