csv ファイル
ヘッダーを考慮すれば次の2つのファイルは、同じデータになります。
cities_header.csv
id,name,population,date_mod
t1271,千葉,59178,2003-9-21
t1272,勝浦,47215,2003-10-15
t1273,市原,83654,2003-6-14
cities_ex02.csv
id,date_mod,population,name
t1271,2003-9-21,59178,千葉
t1272,2003-10-15,47215,勝浦
t1273,2003-6-14,83654,市原
ふたつ目のファイルは次のようにして作成しました。
awk -F, '{print $1","$4","$3","$2}' cities_header.csv > cities_ex02.csv
csv を読むプログラム
csv_header.py
#! /usr/bin/python
#
# csv_header.py
#
# Jun/23/2024
# ------------------------------------------------------------------
import sys
import csv
import json
# ------------------------------------------------------------------
def file_write_proc(file_name,str_out):
fp_out = open(file_name,mode='w')
fp_out.write(str_out)
fp_out.close()
#
# ------------------------------------------------------------------
file_csv=sys.argv[1]
file_json=sys.argv[2]
#
with open(file_csv, "r") as f:
csvreader = csv.DictReader(f)
rows = list(csvreader)
#
out_str = json.dumps(rows)
file_write_proc(file_json,out_str)
# ------------------------------------------------------------------
実行
./csv_header.py cities_header.csv cities.json
./csv_header.py cities_ex02.csv cities_ex02.json
実行結果
ヘッダーが考慮されて読み込まれていることを確認
$ jq . cities.json
[
{
"id": "t1271",
"name": "千葉",
"population": "59178",
"date_mod": "2003-9-21"
},
{
"id": "t1272",
"name": "勝浦",
"population": "47215",
"date_mod": "2003-10-15"
},
{
"id": "t1273",
"name": "市原",
"population": "83654",
"date_mod": "2003-6-14"
}
]
$ jq . cities_ex02.json
[
{
"id": "t1271",
"date_mod": "2003-9-21",
"population": "59178",
"name": "千葉"
},
{
"id": "t1272",
"date_mod": "2003-10-15",
"population": "47215",
"name": "勝浦"
},
{
"id": "t1273",
"date_mod": "2003-6-14",
"population": "83654",
"name": "市原"
}
]