Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
tfile_context_manager.py
Go to the documentation of this file.
1## \file
2## \ingroup tutorial_io
3## \notebook -nodraw
4## This tutorial demonstrates the usage of the TFile class as a Python context
5## manager.
6##
7## \macro_code
8## \macro_output
9##
10## \date March 2022
11## \author Vincenzo Eduardo Padulano CERN/UPV
12import os
13
14import ROOT
15from ROOT import TFile, gROOT
16
17# By default, objects of some ROOT types such as `TH1` and its derived types
18# are automatically attached to a ROOT.TDirectory when they are created.
19# Specifically, at any given point of a ROOT application, the ROOT.gDirectory
20# object tells which is the current directory where objects will be attached to.
21# The next line will print 'PyROOT' as the name of the current directory.
22# That is the global directory created when using ROOT from Python, which is
23# the ROOT.gROOT object.
24print("Current directory: '{}'.\n".format(ROOT.gDirectory.GetName()))
25
26# We can check to which directory a newly created histogram is attached.
27histo_1 = ROOT.TH1F("histo_1", "histo_1", 10, 0, 10)
28print("Histogram '{}' is attached to: '{}'.\n".format(histo_1.GetName(), histo_1.GetDirectory().GetName()))
29
30# For quick saving and forgetting of objects into ROOT files, it is possible to
31# open a TFile as a Python context manager. In the context, objects can be
32# created, modified and finally written to the file. At the end of the context,
33# the file will be automatically closed.
34path = str(gROOT.GetTutorialDir()) + '/io/'
35filename = path+"tfile_1.root"
36with TFile.Open(filename, "recreate") as f:
37 histo_2 = ROOT.TH1F("histo_2", "histo_2", 10, 0, 10)
38 # Inside the context, the current directory is the open file
39 print("Current directory: '{}'.\n".format(ROOT.gDirectory.GetName()))
40 # And the created histogram is automatically attached to the file
41 print("Histogram '{}' is attached to: '{}'.\n".format(histo_2.GetName(), histo_2.GetDirectory().GetName()))
42 # Before exiting the context, objects can be written to the file
43 f.WriteObject(histo_2, "my_histogram")
44
45# When the TFile.Close method is called, the current directory is automatically
46# set again to ROOT.gROOT. Objects that were attached to the file inside the
47# context are automatically deleted, so they can't be accessed anymore after
48# the file is closed.
49print("Status after the first TFile context manager:")
50print(" Current directory: '{}'.".format(ROOT.gDirectory.GetName()))
51# print(histo_2) # the object is deleted at this point, so don't use it anymore!
52
53# Also reading data from a TFile can be done in a context manager. Information
54# stored in the objects of the file can be queried and used inside the context.
55# After the context, the objects are not usable anymore because the file is
56# automatically closed. This means you should use this pattern as a quick way
57# to get information or modify objects from a certain file, without needing to
58# keep the histograms alive afterwards.
59
60with TFile.Open(filename, "read") as f:
61 # Retrieve histogram using the name given to f.WriteObject in the previous
62 # with statement
63 histo_2_fromfile = f["my_histogram"]
64 print("Retrieved '{}' histogram from file '{}'.\n".format(histo_2_fromfile.GetName(), f.GetName()))
65
66# Cleanup the file created for this tutorial
67os.remove(filename)
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t format
static TFile * Open(const char *name, Option_t *option="", const char *ftitle="", Int_t compress=ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault, Int_t netopt=0)
Create / open a file.
Definition TFile.cxx:4086