Arcpy调用ListRasters无法列出文件夹中栅格数据的问题求助
问题
我正在为课程期末项目编写Arcpy脚本,需求是:列出文件夹中的栅格数据,将其添加至GDB,用Shapefile裁剪后计算NDVI。但执行脚本时,arcpy.ListRasters()返回0条栅格数据——这些栅格是从USGS Earth Explorer下载的,我已经试过把文件移到其他路径,问题还是没解决。当前使用的代码如下:
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")
解决方案
针对arcpy.ListRasters()无法识别USGS下载的TIFF栅格的问题,可尝试以下几种排查和解决方法:
修正格式参数:Arcpy的
ListRasters格式参数对大小写敏感,USGS的GeoTIFF需要用"TIFF"而非"TIF",也可以用"ALL"匹配所有栅格格式:raster_list = arcpy.ListRasters("*", "TIFF") # 或匹配所有栅格 raster_list = arcpy.ListRasters("*", "ALL")设置ArcPy环境工作空间:仅定义
workspace变量不够,必须通过arcpy.env.workspace指定ArcPy的工作空间,否则ListRasters无法正确遍历目标文件夹:arcpy.env.workspace = workspace # 在检查工作空间存在后添加这行代码验证单个栅格的可访问性:用
arcpy.Exists()检查单个栅格文件,确认ArcPy能否读取该文件:test_raster_path = os.path.join(workspace, "你的栅格文件名.tif") print(arcpy.Exists(test_raster_path))如果返回
False,说明文件可能损坏、权限不足,或是ArcGIS不支持该栅格的压缩/版本格式。手动遍历筛选文件:如果ListRasters仍失效,用Python原生方法遍历文件夹,手动筛选栅格文件:
raster_list = [] for filename in os.listdir(workspace): if filename.lower().endswith(('.tif', '.tiff')): full_path = os.path.join(workspace, filename) if arcpy.Exists(full_path): raster_list.append(filename)
内容的提问来源于stack exchange,提问作者Fabio Giacomelli
相关产品推荐
相关产品推荐

