LoginSignup
24
33

More than 5 years have passed since last update.

Python + h5py で HDF5 ファイルの読み書き

Posted at
# encoding: utf-8


import h5py


# 書き込むデータ
x = 100
a = [1, 2, 3, 4, 5]

# 書き込み
with h5py.File('output.h5', 'w') as f:

    f.create_dataset('x', data=x)
    f.create_dataset('a', data=a)

# 読み込み
with h5py.File('output.h5', 'r') as f:

    print(f.keys())      # => ['a', 'x']
    print(f['x'].value)  # => 100
    print(f['a'].value)  # => [1 2 3 4 5]
    print(f['a'].shape)  # => (5,)
    print(f['a'].dtype)  # => int64


# グループを作成する
with h5py.File('output_group.h5', 'w') as f:

    f.create_group('hoge')
    f['hoge'].create_dataset('x', data=x)
    f['hoge'].create_dataset('a', data=a)

    # これで以下のようなグループとデータセットが作成される
    #
    # output_group.h5 --- Group 'hoge'
    #                      |
    #                      +- Dataset 'x'
    #                      |
    #                      +- Dataset 'a'

    # 他の書き方
    f.create_group('fuga')
    f.create_dataset('/fuga/x', data=200)
    f.create_dataset('/fuga/a', data=[10, 20, 30, 40, 50])
    # この場合 create_group は省略可
    # '/fuga/x' の先頭のスラッシュは省略可 ('fuga/x' で OK)

with h5py.File('output_group.h5', 'r') as f:

    print(f['hoge']['x'].value)  # => 100
    print(f['hoge']['a'].value)  # => [1 2 3 4 5]

    # 他の書き方
    print(f['fuga/x'].value)  # => 200
    print(f['fuga/a'].value)  # => [10 20 30 40 50]
    # ここでも '/fuga/x' の先頭のスラッシュは省略可 ('fuga/x' で OK)
  • h5py は pip でインストールする。公式ドキュメントは http://docs.h5py.org/en/latest/index.html
  • コンテキストマネージャ (with 文) を使わない場合、自分で f.close() する。書き込み時にはクローズする前に f.flush() してメモリバッファの内容をストレージに書き込む (close() 実行時に暗黙に呼ばれるらしいけど、未検証)。
  • File のモードと挙動
モード 挙動 既存ファイルあり 既存ファイルなし
r リードオンリー エラー
r+ 読み書き エラー
w 書き込み 上書き 新規作成
w- or x 書き込み エラー 新規作成
a 読み書き 上書き 新規作成
24
33
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
24
33