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

今天我们来学习一个关于使用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')

                                                                            更多内容,请关注公众号

                                                                  

 

 

 

转载自:https://blog.csdn.net/u010608964/article/details/87895770

You may also like...