あれもPython,これもPython

Pythonメモ※本サイトはアフィリエイトを利用しています

Pythonの辞書を様々なファイル形式で保存する

Pythonの辞書{}をファイルなどに永続化する方法は複数あります。

import json

d = {'test':1}

# jsonファイルとして保存
with open('json.json','w') as f:
    json.dump(d,f)

# json stringとしてテキストファイルに保存
with open('json.txt','w') as f:
    txt = json.dumps(d)
    f.write(txt)

import pickle
# pickleとして保存
with open('json.pcl','w') as f:
    pickle.dump(d,f)