Search code examples
pythonfileglob

Select files within list of files imported with glob


I am importing a list of files with glob with this code:

fileList = glob.glob('./final_clim/*.shp')

I then need to loop through this selecting certain files and running a loop through these. I have tried editing the string or using list comprehension but I have 2 sets of numbers in the filename and can't work out how to do this. Example file names are:

gla14_eco_23_clim_23

gla14_eco23_clim_24

gla14_eco24_clim_23

So I need all the 'eco23' files grouped together in order to run some code and then 'eco24' but I have hundreds of 'ecos'so can't just split manually.

I have tried:

for file in fileList:
    eco = [f for f in fileList if ("eco_23", f)

I have tried using re.findall but can't quite work it out

I have also tried:

for file in fileList:
    hd, tl = path.split(file)
    name = tl.replace('gla14_eco_', "") etc..

I can't seem to work out how to do this. I could potentially use a dict to replace the last 2 numbers with letters to maybe make this easier? Can anyone help?


Solution

  • Your list comprehension needs correction I believe.

    for i in range(0,825):
        eco = [f for f in fileList if 'eco_'+str(i)+'_' in f]