← Back to list

[SOLVED] glob, loops and local variables

Ted James · 2024-05-20 10:46 · 0 claps · 1.2 min read paywalled
#python #loop #glob
Open on Medium ↗

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())

Answered By — Dani Mesejo

Answer Checked By — Timothy Miller (FixIt Admin)

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0


메타데이터
post_id
e111e0c7dc6c
slug
solved-glob-loops-and-local-variables-e111e0c7dc6c
url
https://medium.com/@fixitblog/solved-glob-loops-and-local-variables-e111e0c7dc6c
canonical_url
https://medium.com/@fixitblog/solved-glob-loops-and-local-variables-e111e0c7dc6c
author_url
https://medium.com/@fixitblog
status
ok
fetched_at
2026-06-17 08:20:12