Change data source of a layer with arcpy.mp

3962
3
10-04-2021 07:53 AM
ParkGIS307
New Contributor

Hello,

Is anyone aware of any useful functions using arcpy.mp that would allow me to select one particular layer in my table of contents and then change the data source of to another file path? 

 

0 Kudos
3 Replies
GaetanPRU
New Contributor III

Hello,

You can do it with updateConnectionProperties() method on aprx object for all layers in a project or layer by layer if datasources are differents :

See example here : https://pro.arcgis.com/fr/pro-app/latest/arcpy/mapping/updatingandfixingdatasources.htm 

GaetanPRU
0 Kudos
ParkGIS307
New Contributor

Thank you for sending me this page with information to updateConnectionProperties(). I did not see any code in here that could change the data source of just one layer in my aprx. For my script I would want to change the data source for just my AOI that could potentially come from a Shapefile that comes from an external source. Can you specify how that might be done? 

0 Kudos
GaetanPRU
New Contributor III

You can try something like this in the console python of your ArcGIS Pro project (or in jupyter notebook window):

import arcpy
aprx=arcpy.mp.ArcGISProject("CURRENT")
map = aprx.listMaps("Map Name with layer")[0]
layer = map.listLayers("Layer Name to change datasource")[0]

#Connection properties are like this for shapefile
#{'dataset': 'XXXXXXX.shp', 'workspace_factory': 'Shape File', 'connection_info': {'database': '[FILE PATH HERE]'}}
cp = layer.connectionProperties
cp['connection_info']['database'] = [NEW FILEPATH]
cp['dataset'] = '[NEW SHAPEFILE NAME].shp'
layer.updateConnectionProperties(l.connectionProperties, cp)

aprx.save()


You have this method in the part 4 of section "Using the connectionProperties dictionary" : https://pro.arcgis.com/fr/pro-app/latest/arcpy/mapping/updatingandfixingdatasources.htm#ESRI_SECTION...

 

GaetanPRU
0 Kudos