Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
_tfile.pyzdoc
Go to the documentation of this file.
1/**
2\class TFile
3\brief \parblock \endparblock
4\htmlonly
5<div class="pyrootbox">
6\endhtmlonly
7## PyROOT
8
9In the same way as for TDirectory, it is possible to get the content of a
10TFile object with the familiar item-getting syntax.
11For more information, please refer to the TDirectory documentation.
12
13In addition, TFile instances can be inspected via the `Get` method, a feature
14that is inherited from TDirectoryFile (please see the documentation of
15TDirectoryFile for examples on how to use it).
16
17In order to write objects into a TFile, the `WriteObject` Python method can
18be used (more information in the documentation of TDirectoryFile).
19
20PyROOT modifies the TFile constructor and the TFile::Open method to make them
21behave in a more pythonic way. In particular, they both throw an `OSError` if
22there was a problem accessing the file (e.g. non-existent or corrupted file).
23
24This class can also be used as a context manager, with the goal of opening a
25file and doing some quick manipulations of the objects inside it. The
26TFile::Close method will be automatically called at the end of the context. For
27example:
28\code{.py}
29from ROOT import TFile
30with TFile("file1.root", "recreate") as outfile:
31 hout = ROOT.TH1F(...)
32 outfile.WriteObject(hout, "myhisto")
33\endcode
34
35Since the file is closed at the end of the context, all objects created or read
36from the file inside the context are not accessible anymore in the application
37(but they will be stored in the file if they were written to it). ROOT objects
38like histograms can be detached from a file with the SetDirectory method. This
39will leave the object untouched so that it can be accessed after the end of the
40context:
41\code{.py}
42import ROOT
43from ROOT import TFile
44with TFile("file1.root", "read") as infile:
45 hin = infile.Get("myhisto")
46 hin.SetDirectory(ROOT.nullptr)
47
48# Use the histogram afterwards
49print(hin.GetName())
50\endcode
51
52\note The TFile::Close method automatically sets the current directory in
53the program to the gROOT object. If you want to restore the status of the
54current directory to some other file that was opened prior to the `with`
55statement, you can use the context manager functionality offered by TContext.
56
57\htmlonly
58</div>
59\endhtmlonly
60*/