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でJSON保存に失敗したら元の設定が壊れた? 一時ファイルとos.replaceで防ぐ方法

0
Posted at

保存先を "w" で開くと、その時点で元の内容が切り詰められます。json.dump() が途中で例外を出すと、設定ファイルには書きかけのJSONが残ることがあります。保存先の親に一時ディレクトリを作り、そこに書き終えてから os.replace() で差し替えると、変換中の失敗から元の設定を守れます。

直書きと差し替えを比べる

元の設定を {"mode":"old"} とし、JSONの標準エンコーダーが変換できない set を渡します。直書きで失敗したあとに設定を戻し、一時ファイル経由の失敗と成功を順に試します。試す場所は一時ディレクトリです。

import json
import os
from pathlib import Path
from tempfile import TemporaryDirectory

def write_json(path, data):
    with path.open("w", encoding="utf-8") as file:
        json.dump(data, file)

def replace_json(path, data):
    with TemporaryDirectory(dir=path.parent) as folder:
        temporary = Path(folder) / path.name
        write_json(temporary, data)
        os.replace(temporary, path)

with TemporaryDirectory() as folder:
    path = Path(folder) / "settings.json"
    old = '{"mode":"old"}'
    invalid = {"mode": "new", "flags": {"fast"}}

    for save in (write_json, replace_json):
        path.write_text(old, encoding="utf-8")
        try:
            save(path, invalid)
        except TypeError as exc:
            print(save.__name__, type(exc).__name__,
                  repr(path.read_text(encoding="utf-8")))

    replace_json(path, {"mode": "new", "flags": ["fast"]})
    print("replaced", json.loads(path.read_text(encoding="utf-8")))
    print("files", sorted(p.name for p in path.parent.iterdir()))
write_json TypeError '{"mode": "new", "flags": '
replace_json TypeError '{"mode":"old"}'
replaced {'mode': 'new', 'flags': ['fast']}
files ['settings.json']

macOS 27.2.1、Python 3.11.14 で実測しました。直書きでは flags の値で止まり、閉じ括弧のないJSONが残りました。差し替え方式では同じ TypeError が出ても元の文字列が残り、正常な入力では新しい設定をJSONとして読み直せました。

AIが書いた保存コードの確認点

  • 保存先を "w" で開いている箇所を探します。例外のログだけでは、ファイルに何が残ったかは分かりません。
  • 一時ファイルを閉じてから差し替えます。この例では write_json() が戻るときにクローズ済みです。書き込みやクローズで例外が出れば、差し替えには進みません。
  • 失敗テストでは例外に加えて元の設定を読み直します。成功時は新しい設定をパースし、値まで確認します。

POSIXでは成功した os.replace() は原子的な操作です。異なるファイルシステム間では失敗し得るため、この例は保存先の親に一時領域を作ります。既存ファイルの権限の引き継ぎや同時更新時の競合対策が必要なら、保存処理に別途組み込みます。停電後の永続化、同時更新、Windowsでの動作は今回の検証範囲外です。

参考 Python公式ドキュメント — os.replace


未経験者向けの体験版を公開しています

※ 中上級者には易しすぎる内容なので、初心者の知り合いへの紹介や社内研修の参考としてどうぞ。

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?