Search code examples
pythontextarcgisarcpy

Exporting attributes of multiple shapefiles to a text file


I'm trying to export the attributes of multiple shapefiles all contained in one folder to a text file. I wrote the code below to do so but it is only exporting the file names to a text file. Any ideas on what I may be doing wrong? I've been troubleshooting and researching for a while.

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  

Solution

  • Here's one way:

    import arcpy
    import csv
    
    f = open(r'C:\\user\\Exports.txt', 'w')
    w = csv.writer(f, lineterminator='\n')
    
    arcpy.env.workspace = "C:\\user\\rainfiles"
    
    shapefileList = arcpy.ListFeatureClasses("*.shp")
    for table in shapefileList:
        f.write("Shapefile:\n")
        f.write(table + "\n")
        fieldList = arcpy.ListFields(table)
        field_names = [field.name for field in fieldList]
        w.writerow(field_names)
        for row in arcpy.SearchCursor(table):
            field_vals = []
            for field in fieldList:
                val = row.getValue(field.name)
                # See if it's a geometry field; if so, use WKT
                try:
                    val = val.WKT
                except AttributeError:
                    # It's not a geometry, and that's okay
                    pass
                field_vals.append(val)
            w.writerow(field_vals)