Thursday, 2 June 2016

python - Using SearchCursor to access & export values in a raster table


I am desperately trying to export the values in a raster table to a .txt file. I've seen some other folk post about this, but for some reason can't get the code to work in my case.


I have a raster, with table already built, called "shed". I simply want to export two fields, "Value" and "Count", to a .txt or .csv file (called "try" in this case). So far, I haven't even been able to get a script that even looks at the raster's table. So far I have:


outfile=open("E:/Weathering_GIS/try.txt",'w')

rows=arcpy.SearchCursor('shed',"","","Value;Count","")
for row in rows:
val=row.getValue('Value')
count=row.getValue('Count')
outfile.write(val)

But "val" and "count" always fail to become anything- they just remain empty values! Am I missing something? Maybe some sort of import I have overlooked?



Answer



I think you were missing closing your output text file - until you do that, you won't get anything written to the text file. Below code tested and works:


import arcpy


arcpy.env.workspace = r"C:\Users\chad\Documents\ArcGIS\Default.gdb"

arcpy.BuildRasterAttributeTable_management("raster17", "Overwrite")
outfile = open(r"D:\temp\raster17.txt", "w")

rows = arcpy.SearchCursor("raster17","","","Value;Count","")
for row in rows:
val = row.getValue("Value")
count = row.getValue("Count")

print val, count
outfile.write(str(val) + "," + str(count) + "\n")

outfile.close()

And it yields this text file:


enter image description here


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...