如何通过python脚本在ArcGIS中添加shapefile?

Tom*_*m W 4 python arcgis arcpy

我正在尝试使用Python自动执行ArcGIS Desktop中的各种任务(通常使用ArcMap),并且我一直需要一种方法来将形状文件添加到当前地图.(然后做一些事情,但这是另一个故事).

到目前为止,我能做的最好的事情是使用以下方法将一个图层文件添加到当前地图("addLayer"是一个图层文件对象):

def AddLayerFromLayerFile(addLayer):
 import arcpy
 mxd = arcpy.mapping.MapDocument("CURRENT")
 df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
 arcpy.mapping.AddLayer(df, addLayer, "AUTO_ARRANGE")
 arcpy.RefreshActiveView()
 arcpy.RefreshTOC()
 del mxd, df, addLayer
Run Code Online (Sandbox Code Playgroud)

但是,我的原始数据总是形状文件,所以我需要能够打开它们.(等效:将形状文件转换为图层文件,无需打开它,但我不想这样做).

Tom*_*m W 6

变量"theShape"是要添加的shape文件的路径.

import arcpy
import arcpy.mapping
# get the map document 
mxd = arcpy.mapping.MapDocument("CURRENT")  

# get the data frame 
df = arcpy.mapping.ListDataFrames(mxd,"*")[0]  

# create a new layer 
newlayer = arcpy.mapping.Layer(theShape)  

# add the layer to the map at the bottom of the TOC in data frame 0 
arcpy.mapping.AddLayer(df, newlayer,"BOTTOM")

# Refresh things
arcpy.RefreshActiveView()
arcpy.RefreshTOC()
del mxd, df, newlayer
Run Code Online (Sandbox Code Playgroud)

  • 嗨,我一直在尝试这个,但继续得到"<type'exception.ValueError'>:Object:CreateObject Layer invalid data source"它适用于.lyr文件,但不是.shp ?? (4认同)