Here’s a little function for exporting an attribute table from ArcGIS to a CSV file. The function takes two arguments, these are a file-path to the input feature class or table and a file-path for the output CSV file (see example down further).
First import the necessary modules.
import arcpy, csv
Inside the function we use ArcPy to get a list of the field names.
def tableToCSV(input_tbl, csv_filepath): fld_list = arcpy.ListFields(input_tbl) fld_names = [fld.name for fld in fld_list]
We then open a CSV file to write the data to.
with open(csv_filepath, 'wb') as csv_file: writer = csv.writer(csv_file)
The first row of the output CSV file contains the header which is the list of field names.
writer.writerow(fld_names)
We then use the ArcPy SearchCursor to access the attributes in the table for each row and write each row to the output CSV file.
with arcpy.da.SearchCursor(input_tbl, fld_names) as cursor: for row in cursor: writer.writerow(row)
And close the CSV file.
csv_file.close()
Full script example…
import arcpy, csv def tableToCSV(input_tbl, csv_filepath): fld_list = arcpy.ListFields(input_tbl) fld_names = [fld.name for fld in fld_list] with open(csv_filepath, 'wb') as csv_file: writer = csv.writer(csv_file) writer.writerow(fld_names) with arcpy.da.SearchCursor(input_tbl, fld_names) as cursor: for row in cursor: writer.writerow(row) print csv_filepath + " CREATED" csv_file.close() fc = r"C:\Users\******\Documents\ArcGIS\Default.gdb\my_fc" out_csv = r"C:\Users\******\Documents\output_file.csv" tableToCSV(fc, out_csv)
Feel free to ask questions, comment, or help build upon this example.
This method has a problem with special characters:
UnicodeEncodeError: ‘ascii’ codec can’t encode character u’\xe3′ in position : ordinal not in range(128)
How to handle this?
LikeLiked by 2 people
Check out https://glenbambrick.com/2017/04/24/osgp-data-assessment/ and scroll down to the ‘Unique Value and Counts’ section. Here I use decode with an iso string to catch Gaelic words/symbols. You need to find out which code you need for non-ascii characters in your attributes.
LikeLike
I ran into the same thing. Trying to decode the text, I ran into different issues, like not being able to decode tuples or integers. So I thought I might try converting the tuples to string (not sure about this being a good idea anyway). My last try was the code below, but now apparently – again – it fails due to encoding when converting to string before the decoding – which I did because otherwise I had integers in the rows…
import arcpy, csv, codecs
def tableToCSV(input_tbl, csv_filepath):
fld_list = arcpy.ListFields(input_tbl)
fld_names = [fld.name for fld in fld_list]
with open(csv_filepath, ‘wb’) as csv_file:
writer = csv.writer(csv_file)
writer.writerow(fld_names)
with arcpy.da.SearchCursor(input_tbl, fld_names) as cursor:
for row in cursor:
row_str = ”.join(str(item) for item in row)
row_dec=row_str.decode(‘utf-8’)
writer.writerow(row_dec)
print csv_filepath + ” CREATED”
csv_file.close()
LikeLike
Hi, many thanks for your script, it is really helpful. However, I would like to ask you how I could do it in a batch for a list of shapefiles. I have been trying different ways without any success.
Many thanks in advance,
LikeLike
Hi Daniel,
Replace the last three lines of code with…
## a list of shapefiles (full paths)
shp_list = [r"full\\path1.shp", r"full\path2.shp"]
## output folder for csv files
ouput_folder = r"folder\\path"
## cycle through the shapefiles
for shpfile in shp_list:
## place csv files in the output folder names the same as the shapefile.csv
out_csv = "{0}\\{1}".format(ouput_folder, shpfile.rsplit("\\")[-1].replace(".shp", ".csv"))
tableToCSV(shpfile, out_csv)
Make sure to indent in the for loop, can seem to format it here.
Let me know how that goes!
LikeLike
Hi again and many thanks for your help!!
It works absolutely fine!!
However, I would like to know your opinion about one question. What happens if I have a list of, for example, 1000 shapefiles? Shall I put all the shapefiles path into the shp_list? It could be a bit tedious and boring to copy and paste 1000 paths.
A possible solution could be work with ListFeatureClasses? I have tried it but it does not work.
Very appreciate for your time and help
LikeLike
Oh, I think I have found the solution. I have just change the line code
shp_list = [r”full\\path1.shp”, r”full\path2.shp”]
for
shp_list = arcpy.ListFeatureClasses()
And it seems to work, but only when the function has been defined previously with your last code, because later on, I have closed the program, opened it again and it gives me the following error.
TypeError: ‘NoneType’ object is not iterable.
Anny solution to avoid this error when I run the script for first time?
Very appreciated again!!
LikeLike
Change the code to
## output folder for csv files
ouput_folder = r”folder\\path”
## folder with shapefiles
arcpy.env.workspace = r”folder\\path\\to\\shapefiles”
## create list
shp_list = arcpy.ListFeatureClasses()
## cycle through the shapefiles
for shpfile in shp_list:
## place csv files in the output folder names the same as the shapefile.csv
out_csv = “{0}\\{1}”.format(ouput_folder, shpfile.rsplit(“\\”)[-1].replace(“.shp”, “.csv”))
tableToCSV(shpfile, out_csv)
again just make sure to indent inside the for loop
LikeLike
Many thanks!!!
It works absolutely fine. However, some shapefiles have special characters and I get the following error:
UnicodeEncodeError: ‘ascii’ codec can’t encode character u’\xc5′ in position 0: ordinal not in range(128)
Looking at google about it, I have imported the next two codes of line at the beginning of the script and it seems to work:
##reload(sys)
##sys.setdefaultencoding(‘utf8’)
The problem now is that I do not get the messages for the user in the interactive window, although the csv files have been created correctly.
LikeLike
Hi thanks a lot for your script
I have multiple raster data and I need to copy the values in excel.
there are two value 0 for snow free area and 1 for snow area I need to copy the values from row no 1.
Actually I have not used coding and I don’t have any idea about it.
could you kindly help me to use your script for my data.
Thanks in Advance
LikeLike