I have a feature class with several fields in the attribute table, and I want to export a few but not all of those fields out to a tab delimited text file. The code below sort of works, half of the fields in the uneeded_fields variable are dropped, but three (SHAPE, long, and utm_y) still end up in my text file. I'm not sure why some of the fields are deleted while the other are passed on to the search cursor. I have tried copying the names from the field set up in Catalog and pasting them into my script so it isn't a typo issue. I'm not sure what I'm missing here.
As a side note, will the SHAPE field always be the first field returned unless specified otherwise? If so del fields[0] can take care of that, but the other will still be a problem.
fields = [f.name for f in arcpy.ListFields(fc)]
uneeded_fields = ('SHAPE', 'OBJECTID', 'lat', 'long','utm_x', 'utm_y')
for i,f in enumerate(fields):
if f in uneeded_fields:
del fields[i]
with open(outfile, 'w') as f:
f.write('\t'.join(fields)+'\n') #column headers
with arcpy.da.SearchCursor(fc, fields) as cursor:
for row in cursor:
f.write('\t'.join([str(r) for r in row])+'\n')