# Arcpy: Geometry object - distanceTo method in a for loop

I'm new to Python so sorry for this maybe trivial question.

I have 4 lines and 4 points, which belong together. I want to get the closest distance from point 4 to line 4, point 3 to line 3, ... . I want to use a SearchCursor and Geometry methods (distanceTo), no geoprocessing tool like "Near".

The code is used so far is:

``````    import arcpy

point_feature = r"C:\Users\name\Documents\ArcGIS\Default.gdb\Gas_points"
line_feature = r"C:\Users\name\Documents\ArcGIS\Default.gdb\Gas_lines"

pointcursor = arcpy.da.SearchCursor(point_feature, ['SHAPE@'])
linecursor = arcpy.da.SearchCursor(line_feature, ['SHAPE@'])

for row in pointcursor:
geometry = pointcursor[0]
print geometry.type
for row in linecursor:
newgeometry = linecursor[0]
print newgeometry.distanceTo(geometry)
``````

The result i get:

point 6.47818694862 67.4681286231 66.0830276147 67.4681286231 point point point

Should be a logical mistake in the for loop, I guess.

You need to reinitialise the linecursor for every point feature iteration

``````import arcpy

point_feature = r"C:\Users\name\Documents\ArcGIS\Default.gdb\Gas_points"
line_feature = r"C:\Users\name\Documents\ArcGIS\Default.gdb\Gas_lines"

pointcursor = arcpy.da.SearchCursor(point_feature, ['SHAPE@'])

for row in pointcursor:
geometry = pointcursor[0]
print geometry.type
linecursor = arcpy.da.SearchCursor(line_feature, ['SHAPE@'])
mindist = 9999999
for row in linecursor:
newgeometry = linecursor[0]
tmpdist = newgeometry.distanceTo(geometry)
if tmpdist < mindist:
mindist = tmpdist
print mindist
``````
• thank you. It works, but i get the distances to all lines, the result i get is: point 6.47818694862 67.4681286231 66.0830276147 67.4681286231 point 30.951053289 5.21964710949 31.5203478296 31.5203478296 point 26.5954440562 26.4388105082 26.5954440562 5.02949987677 point 44.846804569 44.846804569 18.5481780641 41.6929056041 I only need the shortest distances to the relevant line (point 3 to line 3, point 4 to line 4 ,...) ...therefore 6.47, 5.21, 5.02, 18.54. Any idea? – Duddel Mar 1 '16 at 9:07
• See my updated answer. You can save the "mindist" value and closest line ID for each point feature. – capie69 Mar 1 '16 at 9:31