[GIS] How to use folders as input/output parameters

arcpy

What I want to do is to go into a folder, find a layer file, pull it into an MXD, then export a jpeg in an output folder. Everything is great except I don't know how to set the input/output folders.

state =  arcpy.GetParameterAsText(0)
In_Folder = arcpy.GetParameterAsText(1)
Out_Folder = arcpy.GetParameterAsText(2)


lyrfile_o = arcpy.mapping.Layer(In_Folder + str(state) + "_O.lyr")
lyrfile_d = arcpy.mapping.Layer(In_Folder + str(state) + "_D.lyr")
lyrfile_lane = arcpy.mapping.Layer(In_Folder + str(state) + "_Lanes_.lyr")
lyrfile_poly = arcpy.mapping.Layer(In_Folder + str(state) + "_Lanes_Polys1.lyr")

and I get an error like:

<type 'exceptions.ValueError'>: Object: CreateObject Layer invalid data source>

It's written in a text editor then brought into a toolbox and parameters set, both types as folders, the first one (state) is a string.

Any ideas?

Best Answer

Suggestions:

  • Use os.path.join to join folder paths to filenames.
  • Use string formatting (either the newer .format() method or the older modulo (%) method) instead of the concatentation operator (+)
  • Do not use output parameters for what are really inputs. In this case the "output" folder is just an input path (string), not an actual piece of data output by your script.
  • Use an output parameter for data that is created within your script, such as the JPEG file you create. This is optional and is meant to facilitate chaining script tools together in ModelBuilder so in some cases (like this one) it is probably not necessary.
  • Use an IDE such as PyScripter to debug your Python scripts. PyScripter allows you to specify command line parameters and debug interactively.

Here's an example of combining the first two suggestions (using the older modulo string formatting which is what I'm more familiar with):

lyrfile_o = arcpy.mapping.Layer(os.path.join(In_Folder, "%s_%s" % (state, "O.lyr")))