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