[[root:root|Getting started with ROOT]] -> [[root:pyroot|Useful pyROOT snippets]] → [[root:pyroot_tfile|Handling TFile files]]
====== Handling TFile files ======
Class references for:
* ''[[https://root.cern.ch/doc/master/classTDirectory.html|TDirectory]]'',
* ''[[https://root.cern.ch/doc/master/classTFile.html|TFile]]''.
===== Adding a directory to a TFile =====
Here is a basic example creating a file with on directory. If you want to create and save an object in this directory, e.g. a tree or histogram, use ''dir.cd()''. Pay attention to the order of creating an object, changing directory (''cd()'') and writing the object!
from ROOT import TFile
file = TFile("tree.root",'update')
# make directory if it does not exist
dir = file.GetDirectory("dir")
if not dir:
print ">>> created dir"
dir = file.mkdir("dir")
# make this directory the current one: everything you write will be saved here
dir.cd()
# make tree, histogram, ...
file.Write("",TFile.kOverwrite)
file.Close()
===== gDirectory =====
Note that ''gDirectory'' is the current directory containing all newly created saved objects, or those saved to this directory. If you just opened a file, this will be your current directory until you close it or use ''cd()'' on some ''TDirectory'' or other ''TFile''. Test the behavior with this macro:
from ROOT import TFile, TTree, TH1F, gDirectory
def printGDirectory():
print ">>> gDirectory.GetName()\n%s" % gDirectory.GetName()
print ">>> gDirectory.pwd()"
gDirectory.pwd()
print ">>> gDirectory.ls()"
gDirectory.ls()
print
print "\ndefault"
printGDirectory()
print ">>> creating a file with some contents"
file = TFile("test.root","recreate")
tree = TTree("tree","tree")
hist = TH1F("hist","hist",100,0,100)
dir1 = file.mkdir("dir1")
printGDirectory()
print ">>> gDirectory.Delete(\"hist\")"
gDirectory.Delete("hist")
printGDirectory()
print ">>> dir1.cd()"
dir1.cd()
printGDirectory()
print ">>> file.Close()"
file.Close()
printGDirectory()