import arcgisscripting, string from cursoriterator import CursorIterator gp = arcgisscripting.create()The next step is to initialize the different variables for this script. The workspace is the path to the directory, file geodatabase, personal geodatabase, sde,... where the script can find the table or feature class that you want to convert. The table is the name of the table or feature class you want to export. The outputpath is the path to file where you want your export to be written to. Be aware that the output directory should exist. If the file doesn't exist it will be created otherwise it will be overwritten. The csvseparator is the column separator for the output file. It could be anything you want. If you want to use tabs you should set this variable to '\t'. The last variable is ignorefields. If a field name in the table or featureclass is equal to a string in this list then this field won't be exported. This can be used for excluding the shape field, the objectid field or other fields you don't want to appear in the output file.
gp.workspace = r'' ## workspace of the table or feature class table = '' ## table or feature class from wich the attributes should be exported outputpath = r'' ## path to the file where the output should be written to csvseparator = ',' ## column separator field ignorefields = [] ##list with fields to ignoreThen we define a function wich purpose is to create a list of fieldnames that are to be exported to the output file. This is done by iterating over the fields cursor that can be accessed by the gp function listfields. The fields that are in the ignorefields list won't be returned.
def get_fieldnames(fields, ignorefields=[]): ignorefieldsupper = map(string.upper, ignorefields) fields = CursorIterator(fields) fields_output = [] for field in fields: if not field.name.upper() in ignorefieldsupper: fields_output.append(field.name) return fields_output fields = gp.listfields(table) fieldnames = get_fieldnames(fields)Now we are going to iterate over the rows in the table or featureclass and create a list with a string representation of each row. For each field we add the value of a field to a list. Then we concactenate this values with the chosen separator and add this to the output list.
rows = gp.searchcursor(table) rows = CursorIterator(rows) output = [] output.append(csvseparator.join(fieldnames)) for row in rows: outputrow = [] for fieldname in fieldnames: outputrow.append(str(row.getvalue(fieldname))) outputrow = csvseparator.join(outputrow) output.append(outputrow)Finally we write the outputlist to the defined outputpath.
f = open(outputpath, 'w') f.write('\n'.join(output)) f.close()
The full code can be found on the arcscripts site.