Search code examples
pythonloopsglob

glob, loops and local variables


My python script loops over many files in the directory and performs some operations on each of the file, storing results for each of the file in specific variables, defined for each file, using exec() function:

# consider all files within the current directory, having pdb extension
pdb_list = glob.glob('*.pdb')
#make a list of the files 
list=[]
# loop over the list and make some operation with each file
for pdb in pdb_list:
        # take file name w/o its extension
        pdb_name=pdb.rsplit( ".", 1 )[ 0 ]
        # save file_name of the file
        list.append(pdb_name)
        #set variable u_{pdb_name}, which will be associated with some function that do something on the corresponded file
        exec(f'u_{pdb_name} = Universe(pdb)')
        exec(f'print("This is %s computed from %s" % (u_{pdb_name}, pdb_name))')
        # plot a graph using matplot liv
        # exec(f'plt.savefig("rmsd_traj_{pdb_name}.png")')

Basically in my file-looping scripts I tend to use exec(f'...') when I need to save a new variable consisted of the part of some existing variable (like a name of the current file, u_{pdb_name})

Is it possible to do similar tasks with the names of variables but avoiding constantly exec() ?


Solution

  • You could try something like this:

    lst = []
    universes = {}
    # loop over the list and make some operation with each file
    for pdb in pdb_list:
        # take file name w/o its extension
        pdb_name = pdb.rsplit(".", 1)[0]
        # save file_name of the file
        lst.append(pdb_name)
        key = f'u_{pdb_name}'
        universes[key] = Universe(pdb)
        print(f"This is {key} computed from {pdb_name}")
    

    To access some value, just do:

    universes[key]  # where key is the variable name
    

    If you want to iterate over all keys and values, do:

    for key, universe in universes.items():
        print(key)
        print(universe.some_function())