nexpy / nexusformat

Provides an API to open, create, plot, and manipulate NeXus data.
Other
13 stars 19 forks source link

How to append data to existing NeXus File? #202

Closed Gigarrum closed 1 year ago

Gigarrum commented 1 year ago

Is there a way to append new data to existing NeXus Files instead of loading the NeXus object, updating it manually and writing again all data into a new file? In other words, something similar to opening a file with mode 'a' instead of 'w' mode.

Was searching on docs and couldn't find if this is possible.

Gigarrum commented 1 year ago

Just found out how to do this here on Tree API module!

This solved my problem:

with nxopen(filepath, mode="a").nxfile as f:
   f.update(nxobject)
rayosborn commented 1 year ago

If you open a file with 'rw' access (equivalent to 'r+' in h5py, which you could also use), then you can make any changes you like without creating a new file. In the example below, I first create the file, by nxopen('mydata.nxs', 'w') and then do another nxopen with 'rw' mode to add something extra. These two could be in completely different Python sessions.

>>> with nxopen('mydata.nxs', 'w') as root:
..:    root['entry'] = NXentry(NXsample(temperature=40.0))
>>> print(root.tree)
root:NXroot
  entry:NXentry
    sample:NXsample
      temperature = 40.0
>>> with nxopen('mydata.nxs', 'rw') as root:
..:    root['entry/sample/mass'] = 12.0
>>> print(root.tree)
root:NXroot
  entry:NXentry
    sample:NXsample
      mass = 12.0
      temperature = 40.0

The 'a' option when opening a file is only needed if you are not sure if the file needs to be created. I wouldn't recommend using the nxfile commands, since they are only meant for lower-level operations.

Gigarrum commented 1 year ago

Thank you for the advice Ray!