I am trying to create an ArcPy script to clip multiple shapefiles (2,000) to the census tracts in LA County. I have successfully run the code on a single shapefile and am trying to convert the code into a form that will loop through all of the shapefiles saved in a folder.
The code should be able to pull in all the different shapefiles and export them as separate Excel files. I do not want to combine all of my shapefiles into a single shapefile for analysis purposes later one. When I run the script below, I only get one Excel output and I should be getting one per shapefile processed.
#import system modules
import arcpy
import os, re
import csv
import numpy
#Set environment workspace, enable file overwrite
from arcpy import env
env.workspace = r"C:\Users\madis\Desktop\Python_Test"
env.overwriteOutput = True
print "Output environment is set to Python_Test"
#Create a file geodatabase to store data
out_folder_path = r"C:\Users\madis\Desktop\Python_Test"
out_name = "Python_Test.gdb"
arcpy.CreateFileGDB_management(out_folder_path, out_name)
print "Geodatabase created."
#Clean up Census layer
arcpy.MakeFeatureLayer_management("CENSUS_TRACTS_2010.shp",
"CENSUS_TRACTS_2010_lyr")
print "Census tract layer created."
#Start for loop here
#Load shapefiles
file_list = [x for x in os.listdir(r"C:\Users\madis\Desktop\Python_Test") if
re.search(".shp$",x)]
for file1 in file_list:
tract_num = file1[:-4] #re.search("Tract(\d+)", file1).group(1)
print("Processing file: %s" %tract_num)
#Set the clip function variables
in_features = "CENSUS_TRACTS_2010.shp"
clip_features = "234502_de388cd-isochrone.shp"
out_feature_class = r"C:\Users\madis\Desktop\Python_Test\Output"
xy_tolerance = ""
#Execute clip
newInput = arcpy.Clip_analysis(in_features, clip_features,
out_feature_class, xy_tolerance)
# Calculate the clipped areas for tracts in isochrone
areaRatioFieldName = 'SQFT_CLIP'
areaRatioFieldType = 'DOUBLE'
arcpy.AddField_management(newInput, areaRatioFieldName,
areaRatioFieldType)
print "Area ratio field added"
#Export results to .xls
arcpy.CalculateField_management(newInput, "SQFT_CLIP",
'!shape.area@squarefeet!', "PYTHON_9.3")
print "Clipped tract areas calculated"
lyr=r"C:\Users\madis\Desktop\Python_Test\Output.shp"
in_table = r"C:\Users\madis\Desktop\Python_Test\Output.shp"
out_table = "Test1.xls"
arcpy.TableToExcel_conversion(in_table, out_table)
print "Export to Excel is complete"