Import multiple files at ones in PyRoot

I have multiple files with similar names like datacard_20_higgs.txt, datacard_30_higgs.txt. I need to run the same command on all of these files. The problem is, that I do not understand how to import all of these files at ones. If I have that the for loop for the command should not be too hart but I cannot import them somehow


ROOT Version: Not Provided
Platform: Not Provided
Compiler: Not Provided


You can encode the files’ names the following way:

Form("datacard_%d_higgs.txt", i)

Where i is a int . You can loop in i

It’s not working because I get the following error:
NameError: global name ‘Form’ is not defined

So what I want is to get the changeing part of those file names so I can use that to create other files with them corresponding to the ones I took it from

Hi,
note that in PyROOT Form is called ROOT.Form.

In python you can do for example

from glob import glob
files = glob("datacard_*_higgs.txt")

files will be a python list containing all file names that match the glob expression.

Cheers,
Enrico

I get that, that is what I am using right now. But I need to access what’s inside * and that is not working

Sorry, it’s not super clear what you mean with “access what’s inside *”, maybe it would be helpful if you posted the code you have (the relevant lines, that is). Also the issue doesn’t seem related to ROOT?

If I understand correctly, for a list of strings of the form "datacard_N_higgs.txt", where N is an integer, you want to extract the value of N. If files is the python list with these strings, one way to do it is:

prefix = "datacard_"
suffix = "_higgs.txt"
for file in files:
   N = int(file[len(prefix):-len(suffix)])

The more general way would be regular expressions.

Hope this helps!
Enrico

Awesome, that worked, thank you so much!
Also is there maybe a way to sort them from lower value to higher? Right now python is making a random order:
210
270
300
290
230
260
220
160
250
180
170
280
190
240
200

Thank you so much though!

You can put the numbers in a python list and sort the list (sorted_list = sorted(list)) – google is your friend for all python-related queries :smile:

Cheers,
Enrico

That is true, I am sorry, I was just excited to get something running for now!
Thank you Enrico!

1 Like

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