(二十二)arcpy开发&利用arcpy实现shapefile文件导出.csv文件

58 篇文章 19 订阅
52 篇文章 79 订阅

今天我们来学习一个关于使用shapefile文件导出csv文件的功能。首先,这里需要遍历shapefile文件。然后将字段值的写入到csv文件中。具体的实现代码如下所示。


#coding=utf-8
import arcpy
import codecs
import sys


def getCount( fc):

    r = arcpy.GetCount_management(fc)
    return int(r.getOutput(0))

def exportTableToCSV( fc, outCSV, userFieldList=[],
                     delimiter=",",
                     exportOID=True,
                     nullFormat=None,
                     exportGeom=False,
                     quoteStrings=True):

    arcpy.AddMessage("\nOptions selected: \nFields: %s \nDelimiter: '%s' Export OID: %s Export Geom: %s" % (
    userFieldList, delimiter, exportOID, exportGeom))
    try:
        f = open(outCSV, 'rb')
        f.close()
    except:
        arcpy.AddMessage("Cannot open output file!\n%s" % outCSV)
        return False


    fieldList = arcpy.ListFields(fc)
    textFieldsIndex = []

    fieldList2 = []
    arcpy.AddMessage("\nFields found in feature class:")
    for field in fieldList:
        arcpy.AddMessage("%s (%s)" % (field.name, field.type))
        if field.type == 'OID':
            if exportOID:
                fieldList2.append(field)
            else:
                continue
        elif field.type == 'Geometry':
            if exportGeom:
                fieldList2.append(field)
            else:
                continue
        else:
            if len(userFieldList) > 0:

                if field.name in userFieldList:
                    fieldList2.append(field)
            elif len(userFieldList) == 0:

                fieldList2.append(field)
    arcpy.AddMessage("\n")

    index = 0
    for field in fieldList2:
        if field.type == 'String':
            textFieldsIndex.append(index)
        index += 1

    header = ""
    fieldList3 = []
    for field in fieldList2:
        fieldName = field.name
        fieldList3.append(fieldName)
        if quoteStrings:
            header += '"%s"%s' % (fieldName, delimiter)
        else:
            header += '%s%s' % (fieldName, delimiter)

    header = header[:-1]
    arcpy.AddMessage("Writing header: %s" % header)
    f = codecs.open(outCSV, encoding='utf-8', mode='a+')
    f.write(header + "\n")
    f.close()

    arcpy.AddMessage("CSV out: Checking contents of text fields for trouble:")
    arcpy.AddMessage("Text Fields: %s" % textFieldsIndex)
    numFields = len(fieldList3)
    rowCount = 0
    totalRows = getCount(fc)
    arcpy.AddMessage("Starting export...")
    import io
    f = io.open(outCSV, encoding='utf-8', mode='a+')
    with arcpy.da.SearchCursor(fc, fieldList3) as c:
        for row in c:
            rowCount += 1
            if rowCount > sys.maxsize:
                return True
            line = ""
            for i in range(numFields):
                contents = row[i]
                if i in textFieldsIndex:

                    if contents is not None:
                        contents = contents.replace(delimiter, "")
                        if quoteStrings:
                            line += '"%s"%s' % (contents, delimiter)
                        else:
                            line += '%s%s' % (contents, delimiter)
                    else:

                        line += '%s%s' % (contents, delimiter)
                else:

                    line += '%s%s' % (contents, delimiter)

            line = line[:-1]
            f.write(line.decode("gbk") + '\n')
            if rowCount % 1000 == 0:

                f.close()
                f = codecs.open(outCSV, encoding='utf-8', mode='a+')
                arcpy.AddMessage("\rExported row %s of %s..." % (rowCount, totalRows)),

    f.close()
    arcpy.AddMessage("\nAll done. %s rows exported." % rowCount)


data="D:\\Data\\中国国界和省界的SHP格式数据\\省界\\bou2_4l.shp";
outCSV="C:\\Users\\qin\\Desktop\\22\\44.csv";
userFieldList=["GBCODE"]
exportTableToCSV(data,outCSV,userFieldList);

最后使用excel软件打开。结果如下图所示。

注意其中代码会出现报错的地方。

 

 

注意一下编码就可以了。

  f.write(line.decode("gbk") + '\n')

                                                                            更多内容,请关注公众号

                                                                  

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yGIS

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值