[GIS] Export attributes of shapefiles into text file

arcpypython

I'm trying to export attributes of multiple shapefiles a text file. I am multiple getting errors when I run my code not sure what the issue is. Any direction as to where to start to fix this would be helpful.

File "C:\users\Export.py", line 7, in
fclist = arcpy.ListFields(table) File "C:\Program Files (x86)\ArcGIS\Desktop10.2\arcpy\arcpy__init__.py", line 1119, in
ListFields
return gp.listFields(dataset, wild_card, field_type) File "C:\Program Files
(x86)\ArcGIS\Desktop10.2\arcpy\arcpy\geoprocessing_base.py", line
344, in listFields
self._gp.ListFields(*gp_fixargs(args, True))) RuntimeError: ERROR 999999: Error executing function.

Heres my code:
import arcpy
from arcpy import env

arcpy.env.workspace = "C:\\user\\rainfiles"
table = "C:\\user\\rain_files"
outWorkspace = "C:\\user"
fclist = arcpy.ListFields(table)
field_names = [field.name for field in fclist] 
for field in fclist:
    with open(r'C:\\user\\Exports.txt', 'w') as f:
        for field in fclist:
            f.write(field + '\n')
with open(r'C:\\user\\Exports.txt', 'r') as f:
    w = csv.writer(f) 
    w.writerow(field_names)            
    for row in arcpy.SearchCursor(table):  
        field_vals = [row.getValue(field.name) for field in fclist]  
        w.writerow(field_vals)
    del row  

Best Answer

As I mentioned in the comments, ListFields on an invalid data source is the probable cause. There are several other issues that are going to trip you up once you solve that though. I took a rough pass at the code

import arcpy
import csv

table = r'your_input'
output = r'your_output'

fields = arcpy.ListFields(table)
field_names = [field.name for field in fields if field.type != 'Geometry'] 

with open(output, 'w') as f:
    w = csv.writer(f) 
    w.writerow(field_names)            
    for row in arcpy.SearchCursor(table):  
        field_vals = [row.getValue(field) for field in field_names]  
        w.writerow(field_vals)
    del row

If you're using at least 10.1, you'd be better off using arcpy.da.SearchCursor.

import arcpy
import csv

table = r'your_input'
output = r'your_output'

fields = arcpy.ListFields(table)
field_names = [field.name for field in fields if field.type != 'Geometry'] 

with open(output, 'w') as f:
    w = csv.writer(f) 
    w.writerow(field_names)            
    with arcpy.da.SearchCursor(table, field_names) as cursor:  
        for row in cursor:
            w.writerow(row)
Related Question