diff --git a/src/pynwb/__init__.py b/src/pynwb/__init__.py index 9ea18efb8..f1681498b 100644 --- a/src/pynwb/__init__.py +++ b/src/pynwb/__init__.py @@ -372,6 +372,24 @@ def export(self, **kwargs): kwargs['container'] = nwbfile super().export(**kwargs) + @staticmethod + @docval({'name': 'path', 'type': (str, Path), 'doc': 'the path to the HDF5 file', 'default': None}, + {'name': 'file', 'type': [h5py.File, 'S3File'], 'doc': 'a pre-existing h5py.File object', 'default': None}, + is_method=False) + def read_nwb(**kwargs): + """ + Helper factory method for reading an NWB file and return the NWBFile object + """ + # Retrieve the filepath + path = popargs('path', kwargs) + file = popargs('file', kwargs) + + # open the file with NWBZarrIO and rad the file + io = NWBHDF5IO(path=path, file=file, mode="r", load_namespaces=True) + nwbfile = io.read() + + # return the NWBFile object + return nwbfile from . import io as __io # noqa: F401,E402 from .core import NWBContainer, NWBData # noqa: F401,E402 diff --git a/tests/integration/hdf5/test_io.py b/tests/integration/hdf5/test_io.py index d68334c89..1932b7680 100644 --- a/tests/integration/hdf5/test_io.py +++ b/tests/integration/hdf5/test_io.py @@ -531,3 +531,31 @@ def test_round_trip_with_pathlib_path(self): with NWBHDF5IO(pathlib_path, 'r') as io: read_file = io.read() self.assertContainerEqual(read_file, self.nwbfile) + + + def test_read_nwb_method_path(self): + + # write the example file + with NWBHDF5IO(self.path, 'w') as io: + io.write(self.nwbfile) + + # test that the read_nwb method works + read_nwbfile = NWBHDF5IO.read_nwb(path=self.path) + self.assertContainerEqual(read_nwbfile, self.nwbfile) + + read_nwbfile.get_read_io().close() + + def test_read_nwb_method_file(self): + + # write the example file + with NWBHDF5IO(self.path, 'w') as io: + io.write(self.nwbfile) + + import h5py + + file = h5py.File(self.path, 'r') + + read_nwbfile = NWBHDF5IO.read_nwb(file=file) + self.assertContainerEqual(read_nwbfile, self.nwbfile) + + read_nwbfile.get_read_io().close()