Convenience functions¶
For a one-shot read or a small edit, fitsy offers module-level helpers. Each one opens the file, does its work, and closes it again:
fitsy.getdata()– pixel array from one HDU, and its header as well whenheader=True.fitsy.getheader()– header of a single HDU.fitsy.getval()/fitsy.setval()/fitsy.delval()– read, write, or delete a single header card without keeping a handle open.fitsy.info()– list of(index, name, ver, kind, dims)tuples.dimsis the axis list for an image and the row count for a table.fitsy.append()– stream a new image HDU onto the end of an existing file without rewriting it.
For repeated access to one file, open it once with
fitsy.open(). That is faster, because each helper above does its
own open and close.
Example¶
"""Module-level convenience functions: `getdata`, `getval`, `setval`,
`delval`, `info` and `append`.
Each one opens the file, does its work, and closes it again. Use them
for a single read or a single write. Use `fitsy.open` instead when you
need several operations on one file.
Run from the repository root:
python examples/python/convenience.py
"""
import os
import tempfile
import fitsy
import numpy as np
with tempfile.TemporaryDirectory() as td:
path = os.path.join(td, "scratch.fits")
fitsy.write(
path,
[
fitsy.image(
np.arange(16, dtype="i2").reshape(4, 4),
header={"OBJECT": "demo"},
)
],
)
# One-shot reads.
arr = fitsy.getdata(path)
print("shape:", arr.shape)
arr2, hdr = fitsy.getdata(path, header=True)
print("OBJECT:", hdr["OBJECT"])
obj = fitsy.getval(path, "OBJECT")
print("getval :", obj)
# One-shot writes (open + edit + atomic rewrite).
fitsy.setval(path, "OBSERVER", value="Edwin Hubble", comment="discoverer")
fitsy.setval(path, "OBJECT", value="NGC 2403")
fitsy.delval(path, "OBSERVER")
# Stream a new HDU onto the end without rewriting the existing
# file. `fitsy.append` takes a raw numpy array and an optional
# header dict, not a builder.
fitsy.append(
path,
np.zeros((2, 2), dtype="f4"),
header={"EXTNAME": "MASK"},
)
# `info` returns a list of (index, name, ver, kind, dims) tuples.
for index, name, ver, kind, dims in fitsy.info(path):
print(f"{index}: {name or '(primary)'} v{ver} {kind} {dims}")