Solved! Go to Solution.
@Xander Bakker , the code runs fine for me and also generates .csv files but they contain only headers.
I am attaching a copy of *.csv files generated and some sample files.
Please help
Regards
John
I changed the code to this and that resulted in csv files with data.
import arcpy, os
ws = r'D:\Xander\GeoNet\Raster2CSV\data'
outPath = r'D:\Xander\GeoNet\Raster2CSV\csv'
outExt = ".csv"
arcpy.env.workspace = ws
rasters = arcpy.ListRasters("*")
for raster in rasters:
rasloc = os.path.join(ws, raster)
fields = '*'
try:
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'
f.write(header)
curs = arcpy.SearchCursor(rasloc)
for row in curs:
lst = [row.getValue(fld.name) for fld in flds]
lst.append(raster)
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
See files attached.
Is there an advantage to using the csv module over just creating a file with .csv extension and writing lines to it like you did in this example? Your way seems much simpler.
the csv module handles way more cases and error checks to its toolset. If you have a well know data structure and you will be using it, then simple is good, should there be a chance that others may be doing it perhaps with poorly formed data, then the csv module is worth a look, just to save writing error checking.
Hello! First of all, sorry to revive an old post.
I'm also new to GIS, and needed something similar to this post, but I'm getting only one row of data from my rasters attribute tables.
The script which I'm replying to is creating the CSV files, generating two from four headers (creates objectid and rastername, but not "value" and "count", which are other columns from my attribute table) and writes just the first line of data from my rasters. I attached one example.
Also, it would be better for me to all this data got into one file, is that possible?
Could someone help?
Thanks!
Looking at the docs for the search cursor, it says that raster fields are not supported:
"Raster fields are not supported."
What does your code look like? ... It would probably be best to create a new topic for your question.
xander_bakker, Thanks a lot for the code, it worked perfectly.
Thanks again for saving my time.
Regards
John