我有一段代码可以在目录中创建一个栅格文件列表:
import arcpy, os
workspace = r'C:\temp'
# Get a list of all files in all subfolders
rasters = []
for dirpath, dirnames, filenames in arcpy.da.Walk(workspace,
topdown = True,
datatype="RasterDataset"):
for filename in filenames:
rasters.append(os.path.join(dirpath, filename))
生成.tif文件列表:
[r'C:\temp\block1\fileA.tif', r'C:\temp\block1\fileB.tif', r'C:\temp\block2\fileA.tif', r'C:\temp\block2\fileB.tif']
如何生成包含重复文件名的列表列表,如下例所示?
[[r'C:\temp\block1\fileA.tif', r'C:\temp\block2\fileA.tif'], [r'C:\temp\block1\fileB.tif', r'C:\temp\block2\fileB.tif']]
答案 0 :(得分:4)
收集字典中的文件,以基本名称键入; collections.defaultdict()
object使这更容易:
from collections import defaultdict
rasters = defaultdict(list)
for dirpath, dirnames, filenames in arcpy.da.Walk(workspace,
topdown = True,
datatype="RasterDataset"):
for filename in filenames:
rasters[filename].append(os.path.join(dirpath, filename))
rasters = rasters.values()
这会将filename
的路径分组到列表中; rasters.values()
构建您想要的列表列表。