How to remove a TTree from a .root file?

Hello,

I have a .root file with two TTree objects: a and b. I know that I want to delete TTree a from the file, so that the file has only the TTree b remaining. For our application, we do not want to do a TreeCopy command of the TTree b in a new .root file. Is it possible to delete a TTree in a way that I described?

I have scanned the RootTalk forum and I have come across these threads about the same topic, but unfortunately there the question is not answered.


Thank you!

[url]Delete RooObject in RooWorkspace

Thank you very much. Based on the information at the thread(s) you pointed me to, I wrote the following piece of code that works. In case it benefits someone else finding this topic in the future, here it is:

#include <string>
#include "TFile.h"
void removeTree(){

  std::string file_name="testnew.root";
  TFile *file=new TFile((file_name).c_str(),"update");
  std::string object_to_remove="test1;1";
  //the object can be a tree, a histogram, etc, in this case "test1" is a TTree
  //notice the ";1" which means cycle 1; to remove all cycles do ";*"
  //if your object is not at the top directory, but in a directory in the .root file, called foo
  // you do first
  //file->cd("foo");
  //then continue with the Delete command which is only applied to the current gDirectory
  gDirectory->Delete(object_to_remove.c_str());
  file->Close();
}

You should specify a particular “cycle” number only if you really know exactly what you are doing and why. Otherwise you should always say “;*”.

Hi,

I tried the suggestion and it seems to work fine. However, I am a bit puzzled that
the size of the file does not change at all if I remove a tree. The tree is not listed anymore
if I look for it in the file but the file size stays totally unchanged - even if I remove all trees.

Is that expected?

Cheers
Andi

The physical ROOT file will never be “shrunk”. The space occupied by the “deleted” contents will be marked as “free” inside and will be reused when you write anything new to this ROOT file again.
The only way to “shrink” a ROOT file is to copy its contents into a new ROOT file.

Hi,

is there any update on this? Is there any method of TFile that can be used to “trigger” the shrinking of the file? I remember that I was “transferring” the content of the file using ‘hadd’ (with just the file to be shrinked), but is not so elegant…

Matteo