LoginSignup
12
10

More than 5 years have passed since last update.

.pickle と .npz でlist・numpy行列を書き込みと読み出し

Last updated at Posted at 2017-10-25

listやnumpyのarrayを保存

Codeの中で計算したlistやnumpyのarrayを書き込みと読み出しする方法。備忘録。

Code (pickle)

まずはpickleから。

import pickle

sample_list = [1,3,5,7,9,2,4,6,8]

#.pickleに書き込み
with open('sample.pickle','wb') as f:
    pickle.dump(sample_list, f)

#.pickleから読み出し
with open('sample.pickle','rb') as f:
    new_list = pickle.load(f)

print(new_list)#[1, 3, 5, 7, 9, 2, 4, 6, 8]

#一致してるか確認
print(sample_list == new_list)#True

Code (npz)

numpyの行列

import numpy as np

a = np.array([1,2,3,4,5])
b = np.array([6,7,8,9,10])

#.npzに書き込み
np.savez('a_and_b.npz',x = a, y = b)

#.npzから読み出し
new_array = np.load('a_and_b.npz')

print(new_array['x'])#[1 2 3 4 5]
print(new_array['y'])#[ 6  7  8  9 10]

#一致してるか確認
print(a == new_array['x'])#[ True  True  True  True  True]
print(b == new_array['y'])#[ True  True  True  True  True]
12
10
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
12
10