欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用Arcpy批量对raster文件进行区统计

程序员文章站 2022-04-11 15:34:51
...
import arcpy
from arcpy import env
from arcpy.sa import *
import arcpy.da as da


arcpy.CheckOutExtension("spatial")
env.overwriteOutput=1

workingDir="D:\\lyj\\code\\"
env.workspace=workingDir+"globe_temp_raster_result"


in_zone_data=workingDir+"country_188\\"+"country_188.shp"
zone_field="COUNTRY"
in_value_rasters=arcpy.ListRasters()


# 读入新的10年数据时,修改以下代码,startYear=1901 startYear=2001...
startYear=2001

for in_value_raster in in_value_rasters:
    print in_value_raster
    # out_table=env.workspace+"\\dbf\\" + in_value_raster + ".dbf"   # 这样方便,但是cal_1901.txt.tif.dbf这样的文件名python会报错,想了半天才发现是这里错了
    out_table=env.workspace+"\\dbf\\"+ str(startYear) +".dbf"   # 1901.dbf,1902.dbf这样的文件名不会报错

    outZSaT=ZonalStatisticsAsTable(in_zone_data,zone_field,in_value_raster,out_table,"DATA","SUM")

    txtfile=env.workspace+"\\txt\\"+str(startYear)+".txt"
    with open(txtfile,"w") as f:                         # 将print的内容写入.txt文件
        fields=['COUNTRY','SUM']                         # 指定要读入的字段
        with arcpy.da.SearchCursor(out_table, fields) as rows:
            for row in rows:
                print('{0},{1}'.format(row[0],row[1]))
                f.write('{0},{1}'.format(row[0],row[1]))
                f.write('\n')                            # 写完一行后换行
    f.close()

    startYear += 1