0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonでオブジェクトをファイルに保存・読み込みをする

Posted at
import json

def save_object(obj, file_path):
    """
    任意のオブジェクトをJSON形式でファイルに出力する関数。
    """
    try:
        with open(file_path, 'w', encoding='utf-8') as file:
            json.dump(obj, file, ensure_ascii=False, indent=4)
        print(f"オブジェクトを {file_path} に保存しました。")
    except (TypeError, IOError) as e:
        print(f"エラーが発生しました: {e}")

def load_object(file_path):
    """
    JSON形式のファイルを読み込み、オブジェクトとして返す関数。
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            obj = json.load(file)
        print(f"{file_path} からオブジェクトを読み込みました。")
        return obj
    except (json.JSONDecodeError, IOError) as e:
        print(f"エラーが発生しました: {e}")
        return None
        
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?