TransWikia.com

Using glob to select all shapefiles in a subfolder within a for loop

Geographic Information Systems Asked by Joel Footring on May 8, 2021

I want to iterate a script through a number of subfolders within the folder TQ. Within each subfolder are a number of shapefiles that I need to merge and then rasterize. I created a for loop to iterate through each subfolder. My script works but only the first shapefile from each folder is selected and rasterized. I want the script to select all the shapefiles within each subfolder but don’t know how make this compatible with the for loop.

My script is:

#for loading multiple subtiles
import glob

folders = glob.glob("C:/Canopy_polygons/TQ/*")

print(folders)

i=1

for folder in folders:

    outfile_tif = 'C:/Desktop/scratch/merged' + str(i) + '.tif'

    outfile_shp = 'C:/Desktop/scratch/merged' + str(i) + '.shp'

    outfile_1m = 'C:/TQ/1m_null/TQ' + str(i) + '.tif'

    outfile_10m = 'C:/TQ/10m/TQ' + str(i) + '.tif'
  
    subtiles = glob.glob("C:/Canopy_polygons/TQ/**/*.shp") 

    processing.runAndLoadResults("native:mergevectorlayers", {'LAYERS':subtile,'CRS':QgsCoordinateReferenceSystem('EPSG:27700'),'OUTPUT':outfile_shp})

    processing.run("gdal:rasterize", {'INPUT':outfile_shp,'FIELD':'MAX','BURN':0,'UNITS':1,'WIDTH':1,'HEIGHT':1,'EXTENT':'merged' + str(i),'NODATA':0,'OPTIONS':'COMPRESS=DEFLATE|PREDICTOR=2|ZLEVEL=9','DATA_TYPE':5,'INIT':None,'INVERT':False,'EXTRA':'','OUTPUT':outfile_tif})

    processing.run("grass7:r.null", {'map':outfile_tif,'setnull':'-99999','null':'0','-f':False,'-i':False,'-n':False,'-c':False,'-r':False,'output':outfile_1m,'GRASS_REGION_PARAMETER':None,'GRASS_REGION_CELLSIZE_PARAMETER':'0','GRASS_RASTER_FORMAT_OPT':'','GRASS_RASTER_FORMAT_META':''})

    processing.run("saga:resampling", {'INPUT':outfile_1m,'KEEP_TYPE':True,'SCALE_UP':'5','SCALE_DOWN':'3','TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX':None,'TARGET_USER_SIZE':'10','TARGET_USER_FITS':'1','TARGET_TEMPLATE':None,'OUTPUT':outfile_10m})

    i=i+1

I know my issue is how I have defined subtile and included the second for loop but I don’t know how best to do so. I want subtile to select all shapefiles within the folder being iterated.

I am using pyQGIS in version 3.14.

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP