I need to write a Arcpy code for a final project for a class. I'm trying to run a script to list the rasters in a folder, add them to a GDB, clip them using a shapefile, and run the clipped rasters through NDVI. However when I try to list the rasters the script is telling me that there is 0 rasters in the folder. I have downloaded the raster files from USGS Earth Explorer.
This is the code I'm trying to use.
import arcpy
import os
# Set the workspace (folder containing raster datasets)
workspace = r"C:\Users\FGiacomelli\Documents\ArcGIS\Projects\Konza\Rasters\R1"
# Check if the workspace exists
if not arcpy.Exists(workspace):
print("Workspace does not exist: {}".format(workspace))
quit()
# Set the arcpy environment to overwrite outputs
arcpy.env.overwriteOutput = True
# Check out the Spatial Analyst extension
arcpy.CheckOutExtension("Spatial")
try:
# List all the TIFF raster datasets in the workspace
raster_list = arcpy.ListRasters("*", "TIF")
if raster_list:
# Print the number of raster datasets
print("Number of Rasters: {}".format(len(raster_list)))
# Print the names of the raster datasets
print("Raster Names:")
for raster in raster_list:
print(raster)
else:
print("No TIFF raster datasets found in the specified workspace.")
except arcpy.ExecuteError:
print(arcpy.GetMessages())
finally:
# Check in the Spatial Analyst extension
arcpy.CheckInExtension("Spatial")
I even tried to move the files to a different location because I though that it could be ESRI not letting me do it for some reason. So far nothing works.
I've been scratching my head over this and can't figure out how to get around it.
It is most likely because you don't set the workspace... You need to use
arcpy.env.workspace.arcpy.env.workspaceis documented with:Source: https://pro.arcgis.com/en/pro-app/latest/arcpy/classes/env.htm
arcpy.ListRastersis such a tool.There is also
arcpy.da.Walkthat doesn't needarcpy.env.workspace. However, that will only work with files and includes the folder's sub directories as well.Source: https://pro.arcgis.com/en/pro-app/latest/arcpy/get-started/listing-data.htm
Alternatively, if you don't want to use
arcpy.env.workspace, you could usepathlib.Path.globinstead ofarcpy.ListRastersto iterate over your tif files as well: