Exporting only certain columns to CSV file in ArcGIS for Desktop?
I have simplified your code and corrected the error by using the da module introduced in 10.1. It greatly streamlines the reading of data using cursors, and used in conjunction with the with
command this code should be more stable than if it used the the older method of file access.
It works by making a list of all the fields and then removing the fields you do not want from the list. This could be done within the list comprehension, but it would be pretty messy and un-pythonic. Once the list of desired fields has been created it is used with the da module to read all of the data in these fields into the cursor. This can then be looped through and written to the file using another list comprehension to join all the fields. This has the benefit of working for any number of fields greater than 0.
import arcpy
fc = 'C:\\antenna_shp\\cables.shp'
CSVFile = 'C:\\antenna_shp\\FinalOutput.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')
I think I've run into the same problem and discovered the reason why your field "Shape" was not being removed. When using this loop:
if field.name in (['OBJECTID', 'Shape', 'Shape_Length']):
fields.remove(field)
I have discovered it is actually only removing every other field. So it will first loop through, remove 'OBJECTID', and then the 'Shape' field goes to the place held previously by 'OBJECTID' in the list, so it moves on to the next one, which would then be 'Shape_Length'.
So it was not specifically the Shape geometry that was preventing it from being removed, just the fact that it removes every other field when using this script.