I need some help with os.walk and defining shapefiles in sub folders

1598
3
04-10-2013 10:42 AM
scottstreisel
New Contributor
So far this is what I have. It works if the shapefiles are in the C:/test_define folder, but it will fail with this error if they are in sub
folders. I am new to this so I am probably missing something simple, but I can't figure it out..

2000-10-Straight hole well.shp
--------------------------------------------------
Failed to execute. Parameters are not valid.
ERROR 000732: Input Dataset or Feature Class: Dataset 2000-10-Straight hole well.shp does not exist or is not supported
Failed to execute (DefineProjection).

My code
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
import os
import arcpy

# Set workspace environment to a folder
WS = "c:/test_define"
arcpy.env.workspace = WS

for (path, dirs, files) in os.walk(WS):
    for name in files:
        if name.endswith(".shp"):
            print name
            print ("-") * 50
            try:
                infc = name
                sr = arcpy.SpatialReference("NAD 1983 UTM Zone 11N")
                arcpy.DefineProjection_management(infc, sr)

                # print messages when the tool runs successfully
                print(arcpy.GetMessages(0))
   
            except arcpy.ExecuteError:
                print(arcpy.GetMessages(2))
   
            except Exception as ex:
                print(ex.args[0])
Tags (2)
0 Kudos
3 Replies
scottstreisel
New Contributor
For some reason its loosing all my formatting.. sorry.
0 Kudos
Luke_Pinner
MVP Regular Contributor
For some reason its loosing all my formatting.. sorry.


Read this: How to post Python code
0 Kudos
Luke_Pinner
MVP Regular Contributor
That's because you're passing just the filename and not the full path of the shapefile to the tool.  It works when the shapefile is in c:/test_define as you have set that as your workspace.

To fix, change
infc = name
to
infc = os.path.join(path,name)
0 Kudos