jsonファイルの読み書き
同じ内容を何度も調べている気がします。
アウトプットしなければ覚えられないという結論に至ったので
jsonファイルの読み書き関数を記事にまとめます。
コード
handle_json_file.py
import json
import os
def write_json_file(path, file_name, data):
"""
辞書データをファイルに書き出す
:param path: 親フォルダのパス
:param file_name: ファイル名
:param data: 辞書データ
"""
file_path_name_with_ext = os.path.join(path, file_name + '.json')
with open(file_path_name_with_ext, 'w') as fp:
json.dump(data, fp)
def load_json_file(path, file_name):
"""
ファイルから辞書データを読み込む
:param path: 親フォルダのパス
:param file_name: ファイル名
:return data: 辞書データ
"""
file_path_name_with_ext = os.path.join(path, file_name + '.json')
with open(file_path_name_with_ext) as fp:
data = json.load(fp)
return data
# Example
data = {}
data['key'] = 'value'
write_json_file('.', 'file-name', data)
data = load_json_file('.', 'file-name')
print(data)