I am wondering when I can access the workspace and its subfolders with Arcpy tools (using ArcGis 10.2).
I have a raster in following directory: E:/folder/sub1/sub2/sub3/raster.tif
Now I set the working directory to sub2:
import arcpy
arcpy.env.workspace = "E:/folder/sub1/sub2"
For some tools, I can access and write files in subfolder sub3 by referring to the subfolder of the workspace:
# load raster in subfolder
r = arcpy.sa.Raster("sub3/raster.tif")
# load and write rasters in subfolder
arcpy.gp.Reclassify_sa("sub3/raster.tif","Value","1 3;2 2;3 1;4 4;NODATA 0", "sub3/outRaster1.tif","DATA")
This works all very well. If I use the .save() method, however, I get an error:
outR = Reclassify("sub3/raster.tif", "Value","1 3;2 2;3 1;4 4;NODATA 0", "DATA")
outR.save("sub3/outRaster2.tif")
RuntimeError: ERROR 000875: Output raster: E:\sub3\outraster2.tif's workspace is an invalid output workspace.
From this error message, I can see that the .save() method is not using the working directory, but is using the E: root directory. I know that I can solve this problem by using
outR.save(arcpy.env.workspace + "/sub3/outRaster2.tif")
but I am wondering when the working directory is used and when not. I looked for more information, but apparently this is not very well documented. Or is it just a bad practice to use subfolders in the working directory?
1 Answer 1
You can check which tools honor the Current Workspace by looking at the "Environments" section toward the bottom of the tool help page. For example, the clip raster tool allows the use of the Current Workspace evironment:
enter image description here
If you are dealing with a single raster image, it is often preferred to explicitly call that file:
raster = "E:/folder/sub1/sub2sub3/raster.tif"
However, if you have a workspace with multiple raster data, the preferred method (i.e. using arcpy
) is to set a workspace. You can then use this workspace with the arcpy.ListRaster()
method.
arcpy.env.workspace = "E:/folder/sub1/sub2sub3"
rasters = arcpy.ListRasters()
I would recommend becoming familiar with the os.path.join() function. os.path.join()
allows you much greater flexibility in handling workspaces. This is how you would handle your particular situation using that method:
import arcpy
raster = "E:/folder/sub1/sub2/sub3/raster.tif"
outws = "E:/folder/sub1/sub2/sub3/sub4"
r = arcpy.sa.Raster(raster)
outR = arcpy.sa.Reclassify(r, "Value","1 3;2 2;3 1;4 4;NODATA 0", "DATA")
outR.save(os.path.join(outws, "outRaster2.tif"))
arcpy.env.workspace
setting.