[GIS] How to export Select By Location result to Excel using Python and ArcPy

arcgis-desktoparcpydbfexcelselect-by-location

I have been using ArcGIS for a few years now but have only started using Python scripting for ArcGIS for a month or so. I am trying to create a script and I am having a hard time trying to get it to work (Error after Error).
In ArcGIS, I have used SELECT BY LOCATION and exported the selected records as a dBASE table into my file. I have been able to create the Python script to help me do this and also to convert it into an Excel file.

import arcpy

fc = 'Z:\\GIS TEST\\Codes\\Codes\\K.Dun\\Export_Output_2.dbf'
CSVFile = 'Z:\\Excel.csv'

fields = [f.name for f in arcpy.ListFields(fc)]

for i,f in enumerate(fields):
    if f == 'Shape' or f == 'Shape_Length' or f == 'OBJECTID':
        del fields[i]

with open(CSVFile, 'w') as f:
    f.write(','.join(fields)+'\n') #csv headers
    with arcpy.da.SearchCursor(fc, fields) as cursor:
        for row in cursor:
            f.write(','.join([str(r) for r in row])+'\n')

This is fine but it requires me to manually use SELECT BY LOCATION and export the dBASE (.dbf) file before I run the script. Is there any script I can write that will allow to SEARCH BY LOCATION then export the selected records into an Excel file all in one go.

I created a SEARCH BY LOCATION script but don't know how i would join them.

import arcpy
arcpy.env.workspace = "Z:\GIS TEST\Select_by_Location"

arcpy.MakeFeatureLayer_management('Bld_Locations.shp', 'Bld_Locations_lyr') 
arcpy.SelectLayerByLocation_management('Bld_Locations_lyr', "WITHIN_A_DISTANCE",
                                       'Breakout_Location.shp', "2000 Meters", "NEW_SELECTION")

Anyone have any ideas?

Please remember my Python knowledge is very limited.

Best Answer

Use your 'Bld_Locations_lyr' Feature Layer as your "input feature class" instead of the dbf file...

import arcpy

arcpy.env.workspace = "Z:\GIS TEST\Select_by_Location"

arcpy.MakeFeatureLayer_management('Bld_Locations.shp', 'Bld_Locations_lyr')
arcpy.SelectLayerByLocation_management('Bld_Locations_lyr', "WITHIN_A_DISTANCE", 'Breakout_Location.shp', "2000 Meters", "NEW_SELECTION")

CSVFile = 'Z:\\Excel.csv'

fields = [f.name for f in arcpy.ListFields('Bld_Locations_lyr')]

for i,f in enumerate(fields):
    if f == 'Shape' or f == 'Shape_Length' or f == 'OBJECTID':
        del fields[i]

with open(CSVFile, 'w') as f:
    f.write(','.join(fields)+'\n') #csv headers
    with arcpy.da.SearchCursor('Bld_Locations_lyr', fields) as cursor:
        for row in cursor:
            f.write(','.join([str(r) for r in row])+'\n')
Related Question