1

How can I save the output of my For loop so that I have a different output name each time?

This is the code I´m using:

import arcpy
from arcpy import env
from arcpy.sa import *
env.workspace = r'C:\Users\lhark\Desktop\SHK\ArcGis_Proj_Canada\shapefiles'
outworkspace = r'C:\Users\lhark\Desktop\SHK\ArcGis_Proj_Canada\KernelDensity'    
fcList = arcpy.ListFeatureClasses ()
for fc in fcList:
    outKDens = KernelDensity(fc,"NONE",4670)
  • Thanks for editing. I am new to this site. Can you tell me how i can formate the code like you did for me or where i can get information on how to do this? – Lasse Feb 15 '18 at 11:36
  • Just highlight the code and click the format button ({}). – PolyGeo Feb 15 '18 at 11:37
1

ListFeatureClasses returns a list of strings, each string is a name (filename) of the FeatureClasses found in your workspace directory. Now KernelDensity returns a raster object that can be saved to disk with the methode save().

What i would now is name the Rasters to the feature class name extended by "_kd" like here:

import arcpy
from arcpy import env
from arcpy.sa import *
import os
env.workspace = r'C:\Users\lhark\Desktop\SHK\ArcGis_Proj_Canada\shapefiles'
outworkspace = r'C:\Users\lhark\Desktop\SHK\ArcGis_Proj_Canada\KernelDensity'    
fcList = arcpy.ListFeatureClasses ()
for fc in fcList:
    outKDens = KernelDensity(fc,"NONE",4670)
    outKDens.save(outworkspace + "/" + os.path.splitext(fc)[0] + "_kd")

If you like to save your output to geotiff (can handle long filenames!), use this extension explicitly:

    outKDens.save(outworkspace + "/" + os.path.splitext(fc)[0] + "_kd.tif")
0

If you look at the help file for the Kernel Density tool, at the bottom is a code sample showing you how to save a raster with a different name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.