Есть много способов сделать это, в зависимости от ваших данных и того, какие инструменты вы хотите использовать:
a) Запись CSV строка за строкой со списками и заголовком
import csv
data_list = [
["Russia", "Moscow", "Russian"],
["US", "Washington, D.C.", "English"],
["Colombia", "Bogotá", "Spanish"]
]
header = ["col1", "col2", "col3"]
def write_csv_from_lists(data, header, filename):
with open(filename, "w") as csv_file:
csv_writer = csv.writer(csv_file)
csv_writer.writerow(header) # write header
for row in data:
csv_writer.writerow(row) # write each row
write_csv_from_lists(data_list, header, "file1.csv")
file1.csv
col1,col2,col3
Russia,Moscow,Russian
US,"Washington, D.C.",English
Colombia,Bogotá,Spanish
б) Запись CSV строка за строкой с диктовкой и заголовком
import csv
data_dict = [
{"col1": "Russia", "col2": "Moscow", "col3": "Russian"},
{"col1": "US", "col2": "Washington, D.C.", "col3": "English"},
{"col1": "Colombia", "col2": "Bogotá", "col3": "Spanish"}
]
header = ["col1", "col2", "col3"]
def write_csv_from_dicts(data, header, filename):
with open(filename, "w") as csv_file:
dict_writer = csv.DictWriter(csv_file, fieldnames=header)
dict_writer.writeheader() # write header
for row in data:
dict_writer.writerow(row) # write each row
write_csv_from_dicts(data_dict, header, "file2.csv")
file2.csv
col1,col2,col3
Russia,Moscow,Russian
US,"Washington, D.C.",English
Colombia,Bogotá,Spanish
в) Написание CSV с пандами
import pandas as pd
data_dict = [
{"col1": "Russia", "col2": "Moscow", "col3": "Russian"},
{"col1": "US", "col2": "Washington, D.C.", "col3": "English"},
{"col1": "Colombia", "col2": "Bogotá", "col3": "Spanish"}
]
def write_csv_pandas(data, filename):
pd.DataFrame(data).to_csv(filename, index=False)
write_csv_pandas(data_dict, "file3.csv")
file3.csv
col1,col2,col3
Russia,Moscow,Russian
US,"Washington, D.C.",English
Colombia,Bogotá,Spanish