Is there a way to work with files from a dictionary with similar names in a loop?

痴心易碎 提交于 2021-02-05 12:26:31

问题


So, I was wondering if there could be a way to use files from a dictionary with similar names in a loop,

I have this dictionaries:

dcm = {}
for filename in os.listdir('./GMATfiles'):
    if fnmatch.fnmatch(filename,'DCM_hydra*.txt'):
       dcm[filename[:11]] = os.path.normpath(''.join(['./GMATfiles', '/', filename]))
       #print(dcm)

#OUT_INPUT
out={}
for filename in os.listdir('./GMATfiles'):
    if fnmatch.fnmatch(filename,'Out_hydra*.txt'):
       out[filename[:11]] = os.path.normpath(''.join(['./GMATfiles', '/', filename]))
       #print(out) 
#MATRIX_INPUT 
mtr={}
for filename in os.listdir('./GMATfiles'):
    if fnmatch.fnmatch(filename,'matrizr_hydra*.txt'):
       mtr[filename[:15]] = os.path.normpath(''.join(['./GMATfiles', '/', filename]))
       #print(mtr)

The names I get from each one of these dictionaries are the same except for a number (for example:DCM_hydra01, DCM_hydra02, DCM_hydra03 etc.)

Then I need to use these files from the dictionaries in some functions:

IFOV1= gi.IFOV_generic(out['Out_hydra01'],mtr['matrizr_hydra01'], dcm['DCM_hydra01'],endpoint)
IFOV2= gi.IFOV_generic(out['Out_hydra02'],mtr['matrizr_hydra02'], dcm['DCM_hydra02'],endpoint)
.
.
.

Is there a way to write a loop that would let me get these IFOV functions without the need of writing them one by one?


回答1:


You can try iterate over dicts by zip() function like example bellow. It gives you list with all functions for all files. But don't forget than len of all dicts should be equals

dcm = {'f1': 'path_to_file'}
out = {'f1': 'path_to_file'}
mtr = {'f1': 'path_to_file'}

IFOV = []

for d, o, m in zip(dcm, out, mtr):
    IFOV.append(
        gi.IFOV_generic(out[o], mtr[m], dcm[d], endpoint)
    )


来源:https://stackoverflow.com/questions/57177781/is-there-a-way-to-work-with-files-from-a-dictionary-with-similar-names-in-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!