Deleting histograms in ROOT files

Deart ROOTers,

I’m trying to delete a histogram inside an existing ROOT file. I’ve read through Deleting a histogram within a root file but was unable to replicate the alleged success reported therein.

My code:

file = ROOT.TFile("/home/rbrener/Analysis/NSW_sTGC/part_testGnam-Gnam2.root", "UPDATE")
file.cd("Histogramming/Gnam2/SHIFT/layers")
gDirectory.Delete("layer_0_time1")
file.Delete("Histogramming/Gnam2/SHIFT/layers/layer_0_time*")
file.Close()

The two ``Delete" lines are attempts of achieving the same result. Effectively that directory contains layer_0_time;1, layer_0_time;2 and layer_0_time;3.

I want to have them deleted. Actually, this is done in order to overwrite that histogram — I am able to write one with the same name but ROOT automatically assigns it an index n+1 where n is the existing-hist-with-the-same-name’s index.

Any help would be highly appreciated!

Roy

_ROOT Version: 6.22/06
_Platform: Linux8664
Compiler: gcc


The simplest is surely to use the command line tool rootrm

% rootrm --help
usage: rootrm [-h] [-i] [-r] FILE [FILE ...]

Remove objects from ROOT files

positional arguments:
  FILE               Input file

optional arguments:
  -h, --help         show this help message and exit
  -i, --interactive  prompt before every removal.
  -r, --recursive    recurse inside directories

Examples:
- rootrm example.root:hist
  Remove the object 'hist' from the ROOT file 'example.root'

- rootrm example.root:dir/hist
  Remove the object 'hist' from the directory 'dir' inside the ROOT file 'example.root'

- rootrm example.root
  Remove the ROOT file 'example.root'

- rootrm -i example.root:hist
  Display a confirmation request before deleting: 'remove 'hist' from 'example.root' ? (y/n) :'

Hi @roy.brener ,
using the full namecycle should work:

gDirectory.Delete("layer_0_time1;1")

For more information about namecycles you can search this forum, e.g. Questions regarding TTree and their NameCycles might be interesting for you.

Also note that when you write an object you can explicitly overwrite the current cycle rather than create a new one by passing TObject::kOverwrite as an option:

histo.Write(0, TObject::kOverwrite)

(on the other hand namecycles are usually harmless and most ROOT APIs will only take into consideration the highest cycle)

Cheers,
Enrico

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.