Pythonで。
sample.csv
year | month | date | name | Math | Chemistry | History |
2020 | 3 | 1 | Charlie | 50 | 60 | 70 |
2020 | 3 | 1 | Ben | 52 | 59 | 66 |
2020 | 3 | 1 | Jeniffer | 90 | 85 | 75 |
2020 | 4 | 2 | Charlie | 60 | 70 | 80 |
2020 | 4 | 2 | Ben | 57 | 64 | 71 |
2020 | 4 | 2 | Jeniffer | 85 | 80 | 70 |
2020 | 5 | 3 | Charlie | 70 | 80 | 90 |
2020 | 5 | 3 | Ben | 62 | 69 | 76 |
2020 | 5 | 3 | Jeniffer | 79 | 74 | 64 |
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 件のコメント:
コメントを投稿