使用arcpy,批量读取多个文件夹的*.shp中的图层,统计提取图层的个数和要素总个数

使用arcpy,批量读取多个文件夹的*.shp中的图层,统计提取图层的个数和要素总个数

python 复制代码
import arcpy
import os
import json
import csv
from datetime import datetime

def analyze_shapefile_folders(root_folder):
    """
    批量分析多个文件夹中的Shapefile文件
    统计每个Shapefile中图层数和要素总个数
    """
    # 存储统计结果
    results = []
    
    # 遍历所有文件夹
    for root, dirs, files in os.walk(root_folder):
        # 查找所有.shp文件
        for file in files:
            if file.endswith('.shp') and not file.startswith('.'):
                shp_path = os.path.join(root, file)
                
                try:
                    # 分析Shapefile
                    feature_count = analyze_single_shapefile(shp_path)
                    
                    # 记录结果
                    results.append({
                        'shp_path': shp_path,
                        'feature_count': feature_count,
                        'analysis_time': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    })
                    
                    print(f"已分析: {shp_path} - 要素数: {feature_count}")
                    
                except Exception as e:
                    print(f"分析 {shp_path} 时出错: {str(e)}")
    
    return results

def analyze_single_shapefile(shp_path):
    """
    分析单个Shapefile文件
    返回要素总数
    """
    try:
        # 获取要素数量
        count = int(arcpy.GetCount_management(shp_path).getOutput(0))
        return count
    except Exception as e:
        print(f"统计 {shp_path} 要素数时出错: {str(e)}")
        return 0

def save_results_to_json(results, output_file):
    """
    将结果保存为JSON文件
    """
    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(results, f, ensure_ascii=False, indent=2)
    print(f"结果已保存至: {output_file}")

def save_results_to_csv(results, output_file):
    """
    将结果保存为CSV文件
    """
    with open(output_file, 'w', newline='', encoding='utf-8') as f:
        fieldnames = ['shp_path', 'feature_count', 'analysis_time']
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        
        writer.writeheader()
        for result in results:
            writer.writerow(result)
    
    print(f"CSV结果已保存至: {output_file}")

def generate_summary_report(results):
    """
    生成汇总报告
    """
    print("\n=== Shapefile分析汇总报告 ===")
    
    if not results:
        print("未找到任何Shapefile文件")
        return
    
    total_shapefiles = len(results)
    total_features = sum(r['feature_count'] for r in results)
    
    # 找出最大和最小的Shapefile
    max_features_shp = max(results, key=lambda x: x['feature_count'])
    min_features_shp = min(results, key=lambda x: x['feature_count'])
    
    print(f"总Shapefile文件数: {total_shapefiles}")
    print(f"总要素数: {total_features}")
    print(f"平均每个Shapefile要素数: {total_features/total_shapefiles:.2f}")
    print(f"要素最多的Shapefile: {max_features_shp['shp_path']} ({max_features_shp['feature_count']} 要素)")
    print(f"要素最少的Shapefile: {min_features_shp['shp_path']} ({min_features_shp['feature_count']} 要素)")

def main():
    """
    主函数
    """
    # 获取用户输入的路径
    root_folder = input("请输入包含Shapefile文件的根目录路径: ").strip()
    
    # 检查路径是否存在
    if not os.path.exists(root_folder):
        print(f"错误: 路径 {root_folder} 不存在")
        return
    
    print("开始批量分析Shapefile文件...")
    print(f"根目录: {root_folder}")
    
    # 分析Shapefile文件
    results = analyze_shapefile_folders(root_folder)
    
    if not results:
        print("未找到任何Shapefile文件")
        return
    
    # 生成时间戳
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    
    # 保存结果
    json_output = f"shapefile_analysis_results_{timestamp}.json"
    csv_output = f"shapefile_analysis_results_{timestamp}.csv"
    
    save_results_to_json(results, json_output)
    save_results_to_csv(results, csv_output)
    
    # 生成汇总报告
    generate_summary_report(results)
    
    print(f"\n分析完成!结果已保存至:")
    print(f"  - {json_output}")
    print(f"  - {csv_output}")

if __name__ == "__main__":
    main()
相关推荐
用户8356290780512 分钟前
使用 Python 为 PowerPoint 演示文稿添加评论
后端·python
阿图灵31 分钟前
OpenCV 绘图五件套:画圆、文本、线段、矩形与椭圆
图像处理·人工智能·python·opencv·计算机视觉·绘图
web行路人36 分钟前
AI全栈之旅 · 第一周总结
python
slacker-kian39 分钟前
HuggingFace API加载模型超时:用 ModelScopeAPI 替代
人工智能·python·transformer·huggingface·blip·modelscope·blipprocessor
七夜zippoe1 小时前
DolphinDB 高可用部署实战:从容灾设计到故障自动转移
开发语言·python·高可用·容灾·dolphindb
l1258651 小时前
# LangGraph Deep Research Agent 全流程设计:多轮研究、人机协同与真实来源管理
数据库·人工智能·python·算法·自然语言处理·oracle·langchain
青少儿编程课堂2 小时前
图形化编程实战:智能交通灯调度台,一个作品讲透循环、条件与广播
c++·python·算法·bfs·信息学竞赛
HAPPY酷2 小时前
python的对象和方法
开发语言·python
the局外人2 小时前
别再背 Chain、Agent、Memory 了:用一条“智能流水线”学会 LangChain
python·langchain·llm
Zane19942 小时前
你以为的性能瓶颈,未必是真的瓶颈:用 cProfile 找到真凶
后端·python