Home | News | Documentation | Download

Write a TDirectory to new TFile


I am trying to write a TDirectory that I get from a TFile to a new TFile (basically want to split the file by directories while keeping the same structure, which seems not possible with rootcp.)
I’ve looked through the available methods in TDirectory and TFile and cannot seem to find a way to do this. Please see a sample snippet where you can see what I am trying to do:

        inFileName = directoryPath + filename
        inputFile = ROOT.TFile(inFileName)
        outdir = inputFile.get(region)
        outfileName = directoryPath + region + "_" + filename
        outputFile = ROOT.TFile(outfileName)

where region is the directory name. Following this, I would like to know if there is some sort of append-type function such that I can do:


Is this possible some how?

_ROOT Version: 6.22
Platform: Not Provided
Compiler: Not Provided

Hi @Ngrieser1,

In general, for any OS, you cannot create a file in a non-existent directory. Therefore, you will have to create directories as needed before opening the output TFile.

The TSystem class has two member functions for creating directories, MakeDirectory() and mkdir(). The latter allows for creating parent directories recursively, e.g.

gSystem->mkdir("foo/bar/", /*recursive=*/kTRUE);

will create the bar/ directory and its foo/ parent directory.


Hi jalopezg,

Thanks for the response. Okay, so I can copy the structure, but how do I copy the input files directory (and it’s objects) to the output files directory after making it?

Hi @Ngrieser1,

IIUC, you want to recreate the TDirectory structure using directories in your filesystem, where each TObject is a file. For that, you can recursively create directories as specified in my last post and make use of the TTree::Get() and TTree::SaveObjectAs() functions to save individual TObject instances to a file.


Hi Jalopezg,

Sorry this isn’t what I want. I basically want to make new TFiles with the same directory structure, but each TFile would only contain one TDirectory. This would keep the same directory system in tact. Maybe it would be even easier to copy the whole TFile, and just delete all but one of the TDirectories (and associated objects)?

Hi @Ngrieser1,

Sorry, I got you wrong in the first place. Then, you would have to get a reference to a TDirectory for the directory of interest, and recursively write all the keys to the output TFile.

You target Python/PyROOT for the implementation, right?


Yes I’d prefer to do it in Python/PyROOT, but if the functionality is not as simple I can always switch to C.