vascobnunes,这是我通过使用Python脚本将多个ogr2ogr指令菊花链式链接在一起的方法来解决此问题。您可以轻松地将其转换为批处理脚本,基本上我只是将ogr2ogr指令(cmd
)连接在一起,然后通过调用os.system(cmd)
,传入我串联在一起的ogr2ogr命令来执行它们。
秘密武器是(如capooti所示)应用OGR_SQL将文件名强加为要追加到合并结果中的源数据集的常量值。
在我的示例中,-sql
标志在代码中处理如下:
-sql "SELECT \'' + filename + '\' AS filename, * FROM ' + filenameNoExt + '"'
但这令人困惑,因为我需要在结果串联中应用单引号和双引号。为此,我必须转义单引号(即\')以“实际”使用它们。因此,为了提高可读性,有助于查看没有变量和转义序列的代码。如果您将文件名假装为特定迭代的“ roads1”,则在ogr2ogr语句中产生的连接看起来像这样:
-sql "SELECT 'roads1.shp' AS filename, * FROM roads1"
这个.py脚本是我从Matt wilkie(一个空的shapefile的克隆),j03lar50n(使用ogrinfo和ogr_sql将一个列添加到shapefile中)和capooti(使用ogr_sql施加一个固定的列值)中窃取的三个技巧的组合在shapefile中的所有记录上)。所以这是完整的脚本:
# merge_shps.py
import os
path = "D:/GIS/01_tutorials/ND_Roads/extracted" # path to your folder of .shp files
merge = "merge_filename" # this will be the name of your merged result
directory = os.listdir(path)
count = 0
for filename in directory:
if ".SHP" in filename.upper() and not ".XML" in filename.upper():
# On the first pass, create a clone and add the filename column.
if count == 0:
# Make a clone (matt wilkie)..
cmd = 'ogr2ogr ' + path + '/' + merge + '.shp ' + path + '/' + filename + ' -where "FID < 0"'
os.system(cmd)
# Add the field (j03lar50n)..
cmd = 'ogrinfo ' + path + '/' + merge + '.shp -sql "ALTER TABLE ' + merge + ' ADD COLUMN filename character(50)"'
os.system(cmd)
# Now populate the data (capooti)..
print "Merging: " + str(filename)
# You'll need the filename without the .shp extension for the OGR_SQL..
filenameNoExt = filename.replace(".shp","")
cmd = 'ogr2ogr -f "esri shapefile" -update -append ' + \
path + '/' + merge + '.shp ' + \
path + '/' + filename + \
' -sql "SELECT \'' + filename + '\' AS filename, * FROM ' + filenameNoExt + '"'
# Uncomment this line to spit the ogr2ogr sentence to the terminal..
#print "\n" + cmd + "\n"
os.system(cmd)
count += 1