pip install tables # the package name; import as `tables`★Needs the HDF5 C library (bundled in the wheels). Also on conda aspytables. Python 3.11+.import tables as tb f = tb.open_file("data.h5", mode="w")★Modes:"r"read,"w"create/overwrite,"a"append/read-write,"r+". Alwaysf.close()or use awithblock.with tb.open_file("data.h5", "a") as f: print(f) # prints the whole tree★The context manager guarantees flush/close. Printing the file shows every node.# forgot to close in "w"/"a"? data may not be flushed to diskgotchaHDF5 buffers writes — callf.flush()or close the file. An unclosed file can also lock it.
g = f.create_group("/", "sensors", "Sensor data")★Groups are like directories under the root"/". Third arg is a human title.createparents=Trueto make intermediate groups.f.root.sensors # natural-name attribute access f.get_node("/sensors/temp") # path access★Navigate by attribute (f.root.sensors.temp) or by path string. Both reach the same node.for node in f.walk_nodes("/", "Table"): print(node)Traverse the tree; filter by class ("Table","Array","Group","Leaf").f.remove_node("/sensors", recursive=True) · f.rename_node(...)Manage the tree: remove, rename, move, or copy nodes.
class Reading(tb.IsDescription): ts = tb.Time64Col() value = tb.Float64Col() name = tb.StringCol(16) valid = tb.BoolCol()★Define a table schema as anIsDescriptionsubclass — each attribute is a typed column. Cols:Int32Col,Float64Col,StringCol(n),BoolCol,Time64Col,EnumCol…t = f.create_table("/sensors", "temp", Reading, "Temp readings")★Create the table under a group. You can also pass a NumPy structured dtype or a sample record instead of anIsDescription.pos = {"x": tb.Float64Col(shape=(3,))} # multidim columnColumns can be multidimensional (arrays per row) viashape=.t.colnames · t.coltypes · t.nrows · t.descriptionIntrospect a table's schema and size.
row = t.row for r in data: row["ts"] = r.ts; row["value"] = r.v row.append() t.flush()★The idiomatic append: fill the Row buffer field-by-field, callrow.append(), thent.flush()to write. Fast for streaming inserts.t.append([(ts1, v1, b"a", True), (ts2, v2, b"b", False)])★Bulk-append a list of tuples / a NumPy structured array — much faster than row-by-row for big batches.arr = t.read() # whole table -> NumPy structured array t.read(start=0, stop=100, step=2)★Read all or a slice into a NumPy recarray.t.col("value")reads one column.for r in t: # iterate rows (out-of-core) print(r["value"])Iterate rows without loading the whole table — the out-of-core workhorse.