Like the title suggests I have this script that worked once before to export the attribute tables of some rasters as CSV files. However when I run this script again, I get an error:

Runtime error
Traceback (most recent call last):
   File "<string>", line 28, in <module>
NameError: name 'row' is not defined

I pieced this script together from some thread a while back performing a similar task. Can someone please help?

import arcpy, os
outExt = "OUTPUT_NAME.csv"
arcpy.env.workspace = ws
rasters = arcpy.ListRasters("*")
for raster in rasters:
    rasloc = os.path.join(ws, raster)
    fields = '*'
        flds = arcpy.ListFields(rasloc)
        header = ','.join([fld.name for fld in flds])
        if len(flds) != 0:
            outCSV = os.path.join(outPath, '{0}{1}'.format(raster, outExt))
            with open(outCSV,'w') as f:
                header += ',RasterName\n'
                curs = arcpy.SearchCursor(rasloc)
                for row in curs:
                    lst = [row.getValue(fld.name) for fld in flds]
                    line = ','.join(str(a) for a in lst)
                    f.write(line + '\n')
    except Exception as e:
        print "Error processing", raster
        print "Error", e
        print "Is raster not integer or is there no attribute table?"
del row, curs

EDIT: I just realized the data is 32-bit floating point. Is this an issue?

  • 1
    Row 28 is del row, curs? Maybe the with statement already closed/deleted them? You are using old cursor, try da.SearchCursor instead. – BERA Sep 11 '19 at 19:03
  • Thanks for your reply. I'm pretty new to Python script, how do i use SearchCursor in place of the old cursor? – seak23 Sep 11 '19 at 20:41
  • For arcpy.da.SearchCursor(), see: desktop.arcgis.com/en/arcmap/10.4/analyze/arcpy-data-access/… (This also demonstrates how to use it with a with block so that you do not need to del curs). – Son of a Beach Sep 11 '19 at 23:13

Quick answer:

Remove the line: del row, curs

Longer answer:

row is out of scope in your del line. The row variable only exists within the for loop that defines it.

So no need to delete it (del row).

I think curs is probably still in scope, but unless you're short of memory, you can get by without explicitly deleting it.

However, if you do your search cursor using a with statement (and using arcpy.da.SearchCursor()) then it will be auto-deleted when it is finished with, so you have no need to use del curs either. So you can get rid of the del line completely that way.

| improve this answer | |

Your Answer

