# Using Python to input datasource of layer into table field

I am using a bit of Python code to create an attribute table field and then I want to populate that field with the layer's datasource.

I have been using addField management and then calculateField management but I don't know how to reference the datasource so I can have it entered into this field.

This is the key bits of the expression:

inFeatures = "feature" #references the feature in the mxd
inFieldName = "fieldname" #references the field in the feature attribute table
expression = ***this is where I am stuck***
arcpy.CalculateField_management(inFeatures, inFieldName, expression)


It works if I enter a literal string as the expression but I want it to reference the datasource for the feature.

• Could you please provide an example of the datasource you are after? Are you looking for the string to the data source (e.g. C:\path\to\your\data.shp)? – Aaron Dec 17 '17 at 19:23
• Please be sure to specify the exact version of software in use with every question (within the body of the question -- not just with a tag) – Vince Dec 17 '17 at 20:17

## 1 Answer

If you are using ArcGIS, use the following code to identify the datasource, and insert this into the field. Couple of observations...The fc must be identified as a layer and the field must be a text field

#setting the variable mxd to the current map document
mxd = arcpy.mapping.MapDocument("CURRENT")

inFeatures = "feature" #references the feature in the mxd
inFieldName = "fieldname" #references the field in the feature attribute table

#pulls the layer and datasource information and inserts into the field
for lyr in arcpy.mapping.ListLayers(mxd, "*insert lyr name"):
if lyr.supports("DATASOURCE"):
print lyr.dataSource
expression = """"{}" = '{}'""".format(inFieldName, lyr.dataSource)
arcpy.CalculateField_management(inFeatures, inFieldName, expression, "PYTHON")

• @Steve if this answer worked for you, please accept it to close the question – MacroZED Dec 21 '17 at 9:38