LoginSignup
2
0

More than 1 year has passed since last update.

Python : 配列をpickleで保存する・読み込む

Last updated at Posted at 2022-05-20

作成日:20220520
言語:Python3.6
記事の用途:自分用メモ

Pythonで出力した変数を一度ファイルに保存し、あとで別のプログラムから使いたい時には、pickleモジュールを使うと便利。

下のコードでは、
まずaというリストをdata.pickleというファイルとして保存し、
次に上で保存したdata.pickleをbという変数に読み込んでいる。

pickle_save_and_load.py
import pickle

### 保存したい配列
a = ['a', 'b', 'c'] # リストやnumpy.ndarrayなどの配列

### pickleで保存(書き出し)
with open('data.pickle', mode='wb') as fo:
  pickle.dump(a, fo)

### pickleで保存したファイルを読み込み
with open('data.pickle', mode='br') as fi:
  b = pickle.load(fi)

参考記事など

  1. pickleについて
    python公式 (※私には難しかった) https://docs.python.org/ja/3/library/pickle.html
    分かりやすいブログ記事 https://blog.amedama.jp/entry/2015/12/05/132520

  2. with文の使い方について
    別記事を参照されたし。

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