備忘録です.
辞書型配列の読込と書込です.
参考はこちら
CSVファイル読込の際には全ての値の型が保持されていないため,毎回データの型を指定する必要があることに注意.
import csv # module
def read_dict(file):
with open(file, newline = "") as f:
read_dict = csv.DictReader(f, delimiter=",", quotechar='"')
ks = read_dict.fieldnames
return_dict = {k: [] for k in ks}
for row in read_dict:
for k, v in row.items():
return_dict[k].append(v) # notice the type of the value is always string.
return return_dict
def write_csv(file, save_dict):
save_row = {}
with open(file,'w') as f:
writer = csv.DictWriter(f, fieldnames=save_dict.keys(),delimiter=",",quotechar='"')
writer.writeheader()
k1 = list(save_dict.keys())[0]
length = len(save_dict[k1])
for i in range(length):
for k, vs in save_dict.items():
save_row[k] = vs[i]
writer.writerow(save_row)