I am having an issue with using arcpy.CopyFeatures_management. I am attempting to copy shape files from a temp directory and write them to a database as feature classes. What is wrong with this code? My print function correctly lists all of the shape files in the temp directory however It then writes one shape to my database directory and gives it the database name.
import arcpy from arcpy import env import os import sys arcpy.env.overwriteOutput = True workspace = "S:\\xxx\\GIS\\" feature_classes = [] walk = arcpy.da.Walk(workspace, datatype="FeatureClass", type="FeatureClass") outWorkspace = "S:\\xxx\\xxx\\xxx.gdb" for dirpath, dirnames, filenames in walk: for filename in filenames: feature_classes.append(os.path.join(dirpath, filename)) print feature_classes for filename in feature_classes: outFeatureClass = os.path.join(outWorkspace, filename.strip(".shp")) arcpy.CopyFeatures_management(filename, outWorkspace)
Where is this variable used in your last loop? outFeatureClass
It is line 7. I print it a few lines down to confirm it picked up all the
shape files. The loop is intended to strip the directories and .shp for
conversion.
I thought that maybe you wanted outFeatureClass in line 16 in place of outWorkspace as in example 2 in the help
That could be it thanks
This is how I would do that. Hope it helps.
import arcpy import os in_path = r'C:\xxx\xxx\shp' out_path = r'C:\xxx\xxx\out.gdb' arcpy.env.workspace = in_path arcpy.env.overwriteOutput = True shapefiles = arcpy.ListFeatureClasses() for shapefile in shapefiles: print 'copying: ' + shapefile[:-4] arcpy.CopyFeatures_management(shapefile, os.path.join(out_path, shapefile[:-4]))
The problem with this is it does not access the sub directories. So it does not work.
You could put your particular subdirectories in a list. Then you could add the shapefile copy loop code that forest knutsen wrote inside a loop that iterates through the subdirectory list.
rootdir = r"C:\xxx\xxx\shp"
subfolders = [
"Folder1",
"Another Folder",
"AndAnother",
]
for folder in myfolders:
arcpy.env.workspace = os.path.join(rootdir, folder)
for shapefile in arcpy.ListFeatureClasses():
print 'copying: ' + shapefile[:-4]
arcpy.CopyFeatures_management(shapefile, os.path.join(out_path, shapefile[:-4]))
Or you could utilize Python's own os.walk() to navigate your folders instead of listing them out.
So there is nothing I can do with this arcpy.da.Walk(workspace, datatype="FeatureClass", type="FeatureClass") which is able to find all of the shapefiles in the sundirectories?
No, you're correct, arcpy.da.Walk() would probably be the best thing to use. I am so used to using it just in a geodatabase that I forgot that it listed folders too.