Select to view content in your preferred language

Loop a function over all files in a folder with Python and GIS

47783
10
02-12-2015 03:57 PM
FrédéricLeTourneux
Deactivated User

Hi,

I am new to python and I'm trying to use the python interface in ArcGIS to loop a function (buffer) over all files in a directory that I specified. I come up with the script below. However, when I run it, no errors are returned, but no files are created, nothing happens. What do I do?

 #Import arcpy
import arcpy
import os

#Naming the directory
rootdir = "C:\\Users\\Fred\\Desktop\\GIS\\ModelBuilder Project\\TEST"

#allowing overwriting
arcpy.env.overwriteOutput = True

#Setting up counter
thectr = 0

#For-loop for looping function over all files in a folder
for subdirs, dirs, files in os.walk(rootdir):

    for file in files:
        if file == '*.shp':
# Variables
            input_layer = files
            output_layer = "C:\\Users\\Fred\\Desktop\\GIS\\ModelBuilder Project\\TEST\\test" + str(thectr)
# Process: Buffer
            arcpy.Buffer_analysis(input_layer, output_layer, "1 Kilometers", "FULL", "ROUND", "ALL", "")
#Update counter
            thectr=thectr+1






I've also tried the script below, with the same result:

# import modules
import arcpy, glob

# folder where shapefiles are stored
folder = 'C:/myfiles/'

# loop through all shapefiles
for shapefile in glob.glob( folder + '*.shp' ):
     arcpy.Buffer_analysis( shapefile, "C:/output/" + shapefile[-8:-4] + "buffer.shp" "100 Feet", "FULL", "ROUND", "LIST", "Distance")

Ideas?

0 Kudos
10 Replies
ToddBlanchette
Frequent Contributor

Since you're trying to list feature classes within a workspace (in your example: shapefiles in a directory) why not stick with arcpy instead of trying to manipulate all the string possibilities? Arcpy.ListFeatureClasses() method will give you all the shapefiles you're looking to buffer and just set the environment to the working directory. This will also help if you move to geodatabases, as windows directory structure won't work to get you your feature classes in there.

Hope this helps,

Todd