2
0

More than 1 year has passed since last update.

【python3】jsonファイルの読み書き

Posted at

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)

参考サイト

PythonでJSONファイル・文字列の読み込み・書き込み

2
0
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
2
0