# Accessing each Leaf in a .root file over a loop to extract its data

**URL:** <https://root-forum.cern.ch/t/accessing-each-leaf-in-a-root-file-over-a-loop-to-extract-its-data/35633>\
**Category:** ROOT\
**Created:** [August 14, 2019, 8:31am UTC](https://root-forum.cern.ch/t/accessing-each-leaf-in-a-root-file-over-a-loop-to-extract-its-data/35633 "2019-08-14T08:31:01Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![kmac](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/k/2bfe46/32.png) [@kmac](https://root-forum.cern.ch/u/kmac)\
**Post date:** [August 14, 2019, 8:31am UTC](https://root-forum.cern.ch/t/accessing-each-leaf-in-a-root-file-over-a-loop-to-extract-its-data/35633/1 "2019-08-14T08:31:01Z")

</div>

Hello Root Experts!!

I have been trying to extract data from a .root file created via simulation to a .txt file with a comma after each entry (so I can use other programs to read it easily), but I’ve hit a wall.  
I am a complete beginner in ROOT and C++ so I’ve been relying on past forum posts here and in Stack Exchange for guidance. I am running ROOT 6.16 on Ubuntu18.04.

I’ve managed to do so for a single leaf (mainly based off [[https://stackoverflow.com/questions/28970124/cern-root-exporting-data-to-plain-text](https://stackoverflow.com/questions/28970124/cern-root-exporting-data-to-plain-text)] )

```auto
#include <iostream>
#include "TFile.h"
#include "TTree.h"
#include <iomanip>
#include <sstream>
#include <string>
#include <fstream>
using namespace std;

void Extract(const char *filename, const char *treename, const char *leafname, const char *output){

  TFile *file=new TFile(filename); // opens the root file  
  TTree *tree=(TTree*)file->Get(treename); // creates the TTree object

  Float_t val[1]; //create variables of the same type

  ofstream myfile;
  myfile.open (output); // open file with name to the file as inputted at start  
  //printing header according to leaf name and entry 
  myfile << leafname<<"_1";
  myfile << '\n'; 
  Int_t n_events=(Int_t)tree->GetEntries(); // define vector of number of events

  for (Int_t i=0;i<n_events;i++){
    // loop over the tree 
    tree->GetEntry(i);
    val[0] = tree->GetLeaf(leafname)->GetValue(0); // get the entry number
    cout << val[0];
    cout << endl; //print to the screen
    myfile << val[0];
    myfile << '\n'; //write to file
    }

  myfile.close();

}

```

But now, I wish to access each leaf automatically through loops so that I don’t have to manually extract each leaf/variable, since the .root file may contain anywhere between 20-100 leaves/variables.  
I’ve come up with the following by changing a few things from above, giving:

```auto
#include <iostream>
#include "TFile.h"
#include "TTree.h"
#include <iomanip>
#include <sstream>
#include <string>
#include <fstream>
using namespace std;

void Extract(const char *filename, const char *treename, const char *output){

  TFile *file=new TFile(filename); // opens the root  
  TTree *tree=(TTree*)file->Get(treename); // creates the TTree object

  Float_t val; //create variables of the same type as leaves to access

  // Store all leaves in a string vector ??
  vector<string> LeafNames;
  LeafNames->GetListOfLeaves();

  ofstream myfile;
  myfile.open (output); // open file with name to the file as inputted at start 
  
  Int_t n_leaves=(Int_t)tree->GetListOfLeaves(); // define vector of number of leaves

  for (Int_t i=0;i<n_leaves;i++){
  //printing header according to extracted leaf name 
  TLeaf* leaf = GetLeaf(LeafName[i]);
  myfile << leaf <<",";
  myfile << '\n'; 
  
	Int_t n_events=(Int_t)tree->GetEntries(); // define vector of number of events
	for (Int_t j=0;j<n_events;j++){
		// Get values for the particular leaf
		tree->GetEntry(j);
		val = tree->GetLeaf(leaf)->GetValue(0);
		//write to file
		myfile << val<<",";
		myfile << '\n';		
	}
  
  }

  myfile.close();

}

```

I know that this doesn’t work, and I am stuck particularly in a method to extract each leaf in the first loop. Most leaves are of type Float\_t, but some may be Int\_t or UInt\_t so I’m also assuming that this may be an issue as I’ve read that the declared variable must be of the same type?

Any help would be muchly appreciated 🙂

Kind Regards

* * *

_ROOT Version:_ 6.16/00  
_Platform:_ Not Provided  
_Compiler:_ Not Provided

* * *

---

<div class="post-metadata">

**Author:** ![Wile\_E\_Coyote](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/wile_e_coyote/32/12417_2.png) [@Wile\_E\_Coyote](https://root-forum.cern.ch/u/Wile_E_Coyote)\
**Post date:** [August 14, 2019, 8:32am UTC](https://root-forum.cern.ch/t/accessing-each-leaf-in-a-root-file-over-a-loop-to-extract-its-data/35633/2 "2019-08-14T08:32:48Z")

</div>

> [@Header files for Trees](https://root-forum.cern.ch/t/header-files-for-trees/16308/2):
>
> “Most recent” documentation about how to generate and use an “analysis skeleton”: [TTree::MakeClass](http://root.cern.ch/root/html534/TTree.html#TTree:MakeClass) (see also [“ROOT User’s Guide” → “Trees” → “Using TTree::MakeClass”](http://root.cern.ch/root/html534/guides/users-guide/Trees.html#using-ttreemakeclass)) [TTree::MakeSelector](http://root.cern.ch/root/html534/TTree.html#TTree:MakeSelector) (see also [“ROOT Primer” → “File I/O and Parallel Analysis” → “N-tuples in ROOT” → “For the advanced user: Processing trees with a selector script”](http://root.cern.ch/root/htmldoc/guides/primer/ROOTPrimer.html#for-the-advanced-user-processing-trees-with-a-selector-script) and [“ROOT User’s Guide” → “Trees” → “Using TTree::MakeSelector”](http://root.cern.ch/root/html534/guides/users-guide/Trees.html#using-ttreemakeselector) and [“ROOT User’s Guide” → “Example Analysis”](http://root.cern.ch/root/html534/guides/users-guide/ExampleAnalysis.html)) [TTree::MakeProxy](http://root.cern.ch/root/html534/TTree.html#TTree:MakeProxy)[ROOT::RDataFrame](https://root.cern.ch/doc/master/classROOT_1_1RDataFrame.html) (uses the [T…](https://root.cern.ch/doc/master/classTTreeReader.html)

BTW. When you post “source code” or “output” here, do remember to enclose them into two lines which contain just three characters ```.

---

<div class="post-metadata">

**Author:** ![sbinet](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/sbinet/32/13166_2.png) [@sbinet](https://root-forum.cern.ch/u/sbinet)\
**Post date:** [August 14, 2019, 8:55am UTC](https://root-forum.cern.ch/t/accessing-each-leaf-in-a-root-file-over-a-loop-to-extract-its-data/35633/3 "2019-08-14T08:55:00Z")

</div>

if your goal is to “just” have a CSV out of a ROOT TTree, then this might help:

- [https://godoc.org/go-hep.org/x/hep/cmd/root2csv](https://godoc.org/go-hep.org/x/hep/cmd/root2csv)

---

<div class="post-metadata">

**Author:** ![kmac](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/k/2bfe46/32.png) [@kmac](https://root-forum.cern.ch/u/kmac)\
**Post date:** [August 15, 2019, 3:21am UTC](https://root-forum.cern.ch/t/accessing-each-leaf-in-a-root-file-over-a-loop-to-extract-its-data/35633/4 "2019-08-15T03:21:04Z")

</div>

Thank you for your response 🙂  
I’ve installed and attempted to use it as suggested but I’m unsure how it works still, as the documentation was rather confusing.  
Was I meant to run a script? For example, like;

```auto
package main
package hep

import (
"go-hep.org/x/hep"
)

func main() {
root2csv -o out.csv -t tree_name -f /path_to_root_file
}

```

Thank you again.

---

<div class="post-metadata">

**Author:** ![sbinet](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/sbinet/32/13166_2.png) [@sbinet](https://root-forum.cern.ch/u/sbinet)\
**Post date:** [August 15, 2019, 10:11am UTC](https://root-forum.cern.ch/t/accessing-each-leaf-in-a-root-file-over-a-loop-to-extract-its-data/35633/5 "2019-08-15T10:11:28Z")

</div>

hi,

(apologies for the belated answer)

yes, `root2csv` is a simple binary that’s meant to be executed either from a script or directly from your shell prompt.

I have put the binaries of the latest Go-HEP release here:

- [https://cern.ch/binet/go-hep/latest](https://cern.ch/binet/go-hep/latest)

(you just have to choose accordingly to your OS and architecture)

On a Linux 64b box, you’d do:

```auto
$> wget https://binet.web.cern.ch/binet/go-hep/latest/root2csv-linux-amd64.exe 
$> chmod +x ./root2csv-linux-amd64.exe
$> ./root2csv-linux-amd64.exe -o out.csv -t mytree -f /data/input.root

```

but if you’ve installed the [Go](https://golang.org) compiler, then it would just be:

```auto
$> go get go-hep.org/x/hep/cmd/root2csv
$> $GOPATH/bin/root2csv -o out.csv -t mytree -f /data/input.root

```

let me know if you need further assistance.

hth,  
-s

---

<div class="post-metadata">

**Author:** ![kmac](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/k/2bfe46/32.png) [@kmac](https://root-forum.cern.ch/u/kmac)\
**Post date:** [August 16, 2019, 4:06am UTC](https://root-forum.cern.ch/t/accessing-each-leaf-in-a-root-file-over-a-loop-to-extract-its-data/35633/6 "2019-08-16T04:06:59Z")

</div>

Hello,

Thank you again for your response 🙂  
I’ve managed to run the program, however, it seems that many of the leaves in my root file are not compatible with it, as it reads an error message “TLeafElement not supported”.

Regards

---

<div class="post-metadata">

**Author:** ![sbinet](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/sbinet/32/13166_2.png) [@sbinet](https://root-forum.cern.ch/u/sbinet)\
**Post date:** [August 16, 2019, 7:13am UTC](https://root-forum.cern.ch/t/accessing-each-leaf-in-a-root-file-over-a-loop-to-extract-its-data/35633/7 "2019-08-16T07:13:26Z")

</div>

bummer.

if you have a small example ROOT file with the same structure, I could try to improve `root2csv`. (`root-dump` knows how to handle some of these `TLeafElement`…)  
or, if you could paste the output of:

```auto
$> root ./my/file.root
[root] auto t = (TTree*)_file0->Get("your tree name");
[root] t->Print();

```

that would help me knowing a bit more about your file&tree structures.

hth,  
-s

---

<div class="post-metadata">

**Author:** ![sbinet](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/sbinet/32/13166_2.png) [@sbinet](https://root-forum.cern.ch/u/sbinet)\
**Post date:** [August 16, 2019, 9:13am UTC](https://root-forum.cern.ch/t/accessing-each-leaf-in-a-root-file-over-a-loop-to-extract-its-data/35633/8 "2019-08-16T09:13:06Z")

</div>

I’ve improved `root2csv` to be able to understand fully-split `TTree`s with `TLeafElement`s that are builtins (+`std::string` and `TString`).

if you update your `go-hep` installation you should be able to pick it up:

```auto
$> go get -u go-hep.org/x/hep/cmt/root2csv

```

alternatively, here is the updated binary for Linux/64b:

- [https://binet.web.cern.ch/binet/go-hep/root2csv-024119d-linux-amd64.exe](https://binet.web.cern.ch/binet/go-hep/root2csv-024119d-linux-amd64.exe)

hth,  
-s

---

<div class="post-metadata">

**Author:** ![Axel](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/axel/32/11084_2.png) [@Axel](https://root-forum.cern.ch/u/Axel)\
**Post date:** [August 19, 2019, 1:59pm UTC](https://root-forum.cern.ch/t/accessing-each-leaf-in-a-root-file-over-a-loop-to-extract-its-data/35633/9 "2019-08-19T13:59:27Z")

</div>

Hi @kmac - keep in mind that this Go code is not part of ROOT - we should have a solution in ROOT proper! @pcanal wouldn’t XMLIO do?

---

<div class="post-metadata">

**Author:** ![system](https://root-forum.cern.ch/uploads/default/original/3X/e/f/efe4f24398fd8ffeb76bccb6ecc46d9d9c003376.png) [@system](https://root-forum.cern.ch/u/system)\
**Post date:** [September 2, 2019, 1:59pm UTC](https://root-forum.cern.ch/t/accessing-each-leaf-in-a-root-file-over-a-loop-to-extract-its-data/35633/10 "2019-09-02T13:59:29Z")

</div>

Closed on September 2, 2019, 1:59pm UTC

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