运行环境

ArcGIS10.2 + Python2.7

目录结构

├—— txt_to_shp.py       # 代码文件
├—— txt                 # 输入目录(界址点目录)
│    └─ a.txt
│    └─ b.txt
├—— shp                 # 输出目录(shp目录)
│    └─ a.shp
│    └─ b.shp

界址点文件结构

界址点文件须为 UTF-8 编码!

[属性描述]
格式版本号=1. 01版本
数据产生单位=
数据产生日期=
坐标系=2000国家大地坐标系
几度分带=3
投影类型=高斯克吕格
计量单位=米
带号=40
精度=0.001
转换参数=0,0,0,0,0,0,0
[地块坐标]
5,0.094817,区块1,,面,,,,@
J1,1,3387534.2754,40540005.543
J2,1,3387530.2234,40540048.8922
J3,1,3387508.1304,40540045.8152
J4,1,3387512.7641,40540003.2538
J1,1,3387534.2754,40540005.543
6,0.101307,,区块2,,面,,,,@
J1,1,3387354.8828,40539798.1376
J2,1,3387345.8625,40539833.6885
J3,1,3387320.3065,40539828.0604
J4,1,3387327.2991,40539791.1546
J1,1,3387354.8828,40539798.1376

代码

# coding=UTF-8
import arcpy
import os
import sys
import codecs
import re  # 用于正则匹配非法符号

# 解决Python 2.7默认编码限制
reload(sys)
sys.setdefaultencoding('utf-8')

# 获取系统文件编码
fs_encoding = sys.getfilesystemencoding()

# 配置路径(支持中文)
rootdir = u'E:\\tmp'
txt_dir = os.path.join(rootdir, u'txt')
shp_dir = os.path.join(rootdir, u'shp')

# 检查并创建目录
if not os.path.exists(shp_dir):
    os.makedirs(shp_dir)

# 设置ArcPy环境
arcpy.env.workspace = shp_dir
arcpy.env.overwriteOutput = True

# 定义空间参考
spatial_ref = arcpy.SpatialReference(4528)

# ArcGIS禁止的特殊符号(\ / : * ? " < > |)
invalid_pattern = re.compile(r'[\\/:\*\?"<>\|]')

# 遍历txt目录下的所有文件
for txt_file in os.listdir(txt_dir.encode(fs_encoding)):
    if txt_file.endswith('.txt'):
        txt_path = os.path.join(txt_dir, txt_file)
        # 生成输出 shp 文件名(与 txt 同名)
        shp_name = os.path.splitext(txt_file)[0] + ".shp"
        shp_path = os.path.join(shp_dir, shp_name)          
       

        # 创建面要素类
        arcpy.CreateFeatureclass_management(
            shp_dir,
            shp_name,
            "POLYGON",
            spatial_reference=spatial_ref
        )

        # 读取txt文件内容(兼容编码)
        # points = []
        try:
            with codecs.open(txt_path, 'r', 'utf-8') as f:
                content = f.read()
        except UnicodeDecodeError:
            with codecs.open(txt_path, 'r', fs_encoding) as f:
                content = f.read()
                
        # 按 "@" 分割不同面要素(注意去除空行)
        features = [f.strip() for f in content.split("@") if f.strip()]
        with arcpy.da.InsertCursor(shp_path,["SHAPE@"]) as cursor:
            for feature in features[1:]:
                #print(feature)
                points=[]
                for line in feature.split('\n'):
                    line=line.strip()
                    if line.startswith('J'):
                        
                        parts=line.split(',')
                        if len(parts)>=4:
                            x = float(parts[2])
                            #print(x)
                            y = float(parts[3])
                            #print(y)
                            points.append(arcpy.Point(y,x))
                            
                
                            
                # 构建并插入多边形            
                polygon = arcpy.Polygon(arcpy.Array(points), spatial_ref)           
                with arcpy.da.InsertCursor(shp_path, ["SHAPE@"]) as cursor:
                    cursor.insertRow([polygon])
               
        
        # 解析界址点
        # for line in content.split('\n'):
            # line = line.strip()
            # if line.startswith('J'):
                # parts = line.split(',')
                # if len(parts) >= 4:
                    # x = float(parts[2])
                    # y = float(parts[3])
                    # points.append(arcpy.Point(y, x))

        # 构建并插入多边形
        # polygon = arcpy.Polygon(arcpy.Array(points), spatial_ref)
        # with arcpy.da.InsertCursor(os.path.join(shp_dir, shp_name), ["SHAPE@"]) as cursor:
            # cursor.insertRow([polygon])

        # print(u"成功转换文件:%s → %s" % (txt_file_unicode, shp_name))



print(u"所有txt文件批量转换完成!")