☆☆ 新着記事 ☆☆

2020年5月21日木曜日

CSVからJSONに変換してみる


Pythonで。

sample.csv


yearmonthdatenameMathChemistryHistory
202031Charlie506070
202031Ben525966
202031Jeniffer908575
202042Charlie607080
202042Ben576471
202042Jeniffer858070
202053Charlie708090
202053Ben626976
202053Jeniffer797464

Step1. CSVファイルの読み込み。

import csv
with open("sample.csv",'r',encoding='utf-8_sig') as f:
    reader = csv.DictReader(f)
    for line in reader:
        print(line)
//Output
OrderedDict([('year', '2020'), ('month', '3'), ('date', '1'), ('name', 'Charlie'), ('Math', '50'), ('Chemistry', '60'), ('History', '70')])
OrderedDict([('year', '2020'), ('month', '3'), ('date', '1'), ('name', 'Ben'), ('Math', '52'), ('Chemistry', '59'), ('History', '66')])
OrderedDict([('year', '2020'), ('month', '3'), ('date', '1'), ('name', 'Jeniffer'), ('Math', '90'), ('Chemistry', '85'), ('History', '75')])
OrderedDict([('year', '2020'), ('month', '4'), ('date', '2'), ('name', 'Charlie'), ('Math', '60'), ('Chemistry', '70'), ('History', '80')])
OrderedDict([('year', '2020'), ('month', '4'), ('date', '2'), ('name', 'Ben'), ('Math', '57'), ('Chemistry', '64'), ('History', '71')])................

*1行目にヘッダーがなく自分で指定したい場合
keys = ('column1', 'column2', 'column3')
with open('sample.csv', 'r') as f:
    for line in csv.DictReader(f, keys):
で、指定できる。

Step2. リストに格納

import csv
new_score=[]
with open("sample.csv",'r') as f:
     reader = csv.DictReader(f)
    
     for line in reader:
         new_score.append(line)

Step3: JSONファイルとして書き出し

import csv
import json
new_score=[]
with open("sample.csv",'r',encoding='utf-8_sig') as f:
     reader = csv.DictReader(f)
     for line in reader:
         new_score.append(line)
with open('sample.json', 'w') as f:
    json.dump(new_score, f)



0 件のコメント:

コメントを投稿