LoginSignup
34
43

More than 5 years have passed since last update.

Pythonにおけるデータ入出力(CSV、JSON)

Posted at

概要

O'Reilly Japan の「PythonとJavaScriptではじめるデータビジュアライゼーション」を参考に、勉強をしています。

module

JSON形式のファイルをCSV形式で出力

# coding:UTF-8
import json
import csv

# JSONファイルのロード
json_dict = json.load(open('data/players.json', 'r'))
# list of dictの抽出
target_dicts = json_dict['players']

with open('data/players.csv', 'w') as f:
    # dialectの登録
    csv.register_dialect('dialect01', doublequote=True, quoting=csv.QUOTE_ALL)
    # DictWriter作成
    writer = csv.DictWriter(f, fieldnames=target_dicts[0].keys(), dialect='dialect01')
    # CSVへの書き込み
    writer.writeheader()
    for target_dict in target_dicts:
        writer.writerow(target_dict)

CSV形式のファイルをJSON形式で出力

# coding:UTF-8
import json
import csv

json_list = []
json_data = {}

# CSVファイルのロード
with open('data/players.csv', 'r') as f:
    # list of dictの作成
    for line in csv.DictReader(f):
        json_list.append(line)

    json_data["players"] = json_list

with open('data/players.json', 'w') as f:
    # JSONへの書き込み
    json.dump(json_data, f)

※上記のソースは、入出力対象のJSONファイルの形式に依存している。

入出力ファイル

JSON形式(players.json)

{
  "players": [
    {
      "id": "0001",
      "name": "Nishikawa Haruki",
      "position": "center fielder"
    },
    {
      "id": "0002",
      "name": "Matsumoto Go",
      "position": "right fielder"
    },
    {
      "id": "0003",
      "name": "Brandon J. Laird",
      "position": "third baseman"
    } ,
    {
      "id": "0004",
      "name": "Nakata Sho",
      "position": "first baseman"
    }
  ]
}

CSV形式(players.csv)

"id","name","position"
"0001","Nishikawa Haruki","center fielder"
"0002","Matsumoto Go","right fielder"
"0003","Brandon J. Laird","third baseman"
"0004","Nakata Sho","first baseman"

参考

書籍

PythonとJavaScriptではじめるデータビジュアライゼーション
https://www.oreilly.co.jp/books/9784873118086/

Python 3.3.6 ドキュメント

14.1. csv — CSV ファイルの読み書き
https://docs.python.jp/3.3/library/csv.html

19.2. json — JSON エンコーダおよびデコーダ
https://docs.python.jp/3.3/library/json.html

34
43
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
43