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.workspace
is documented with:
Tools that honor the Current Workspace environment use the workspace specified as the default location for geoprocessing tool inputs and outputs.
Source: https://pro.arcgis.com/en/pro-app/latest/arcpy/classes/env.htm
arcpy.ListRasters
is such a tool.
arcpy.env.workspace = r"C:\Users\FGiacomelli\......\R1"
There is also arcpy.da.Walk
that doesn't need arcpy.env.workspace
. However, that will only work with files and includes the folder's sub directories as well.
Unlike the list functions, Walk does not use the workspace environment to identify its starting workspace. Instead, the first starting (or top) workspace that Walk traverses is specified in its first argument, top.
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 use pathlib.Path.glob
instead of arcpy.ListRasters
to iterate over your tif files as well:
from pathlib import Path
workspace = r"C:\Users\FGiacomelli\Documents\ArcGIS\Projects\Konza\Rasters\R1"
rasters = [raster for raster in Path(workspace).glob("*.tif")]
print(f"Number of Rasters: {len(rasters)}")
for raster in rasters:
print(raster)