python - How to create a list within a list of duplicate files? -
i have section of code creates list of raster files within directory:
import arcpy, os workspace = r'c:\temp' # list of files in subfolders rasters = [] dirpath, dirnames, filenames in arcpy.da.walk(workspace, topdown = true, datatype="rasterdataset"): filename in filenames: rasters.append(os.path.join(dirpath, filename))
which produces list of .tif files:
[r'c:\temp\block1\filea.tif', r'c:\temp\block1\fileb.tif', r'c:\temp\block2\filea.tif', r'c:\temp\block2\fileb.tif']
how can generate list of lists contain duplicate file names, following example?
[[r'c:\temp\block1\filea.tif', r'c:\temp\block2\filea.tif'], [r'c:\temp\block1\fileb.tif', r'c:\temp\block2\fileb.tif']]
collect files in dictionary, keyed base name; collections.defaultdict()
object makes easier:
from collections import defaultdict rasters = defaultdict(list) dirpath, dirnames, filenames in arcpy.da.walk(workspace, topdown = true, datatype="rasterdataset"): filename in filenames: rasters[filename].append(os.path.join(dirpath, filename)) rasters = rasters.values()
this groups paths filename
lists; rasters.values()
builds desired list-of-lists.
Comments
Post a Comment