🙂

Pythonの変数をシリアアライズとファイルへの保存

2022/02/12に公開

はじめに

Zennの記事編集の練習も兼ねてPythonの変数をシリアライズしてファイルへ保存し、そのファイルから変数を復帰する方法について記載します。

Pythonでシリアリズしファイルへ保存

test1.py
import pickle

def write_to_file(file,data):
    f = open(file,'wb')
    pickle.dump(data,f)
    f.close()

d1 = [1,2,3,4,5]
d2 = {
    "test1":1,
    "test2":"2",
    "test3":{
        "A":"3-1",
        "B":"3-2",
        "C":"3-3",
    }
}

list1 = []
list1.append(d1)
list1.append(d2)
list1.append("END")

print("list1=",list1)
write_to_file("t1.txt",list1)

exit(0)

実行結果

# python3 test1.py
list1= [[1, 2, 3, 4, 5], {'test1': 1, 'test2': '2', 'test3': {'A': '3-1', 'B': '3-2', 'C': '3-3'}}, 'END']
t1.txtの内容
# od -tx1 t1.txt
0000000 80 04 95 5d 00 00 00 00 00 00 00 5d 94 28 5d 94
0000020 28 4b 01 4b 02 4b 03 4b 04 4b 05 65 7d 94 28 8c
0000040 05 74 65 73 74 31 94 4b 01 8c 05 74 65 73 74 32
0000060 94 8c 01 32 94 8c 05 74 65 73 74 33 94 7d 94 28
0000100 8c 01 41 94 8c 03 33 2d 31 94 8c 01 42 94 8c 03
0000120 33 2d 32 94 8c 01 43 94 8c 03 33 2d 33 94 75 75
0000140 8c 03 45 4e 44 94 65 2e

Pythonでファイルからデリシアライズ

test2.py
import pickle

def read_from_file(file):
    f = open(file,'rb')
    data = pickle.load(f)
    f.close()
    return data

list2 = read_from_file("t1.txt")
print("list2=",list2)

実行結果

# python3 test2.py
list2= [[1, 2, 3, 4, 5], {'test1': 1, 'test2': '2', 'test3': {'A': '3-1', 'B': '3-2', 'C': '3-3'}}, 'END']

感想

結構使いやすいですね。

Markdownの記法

https://zenn.dev/zenn/articles/markdown-guide

Discussion