Python arcpy.CopyFeatures_management() Examples

The following are 12 code examples of arcpy.CopyFeatures_management(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module arcpy , or try the search function .
Example #1
Source File: CreateDischargeMap.py    From python-toolbox-for-rapid with Apache License 2.0 7 votes vote down vote up
def copyFlowlines(self, in_drainage_line, path_database, list_uniqueID):
        """Create copies of flowlines based on the layer query definitions"""
        # make a feature layer for query selection
        name_lyr = "flowlines"
        arcpy.MakeFeatureLayer_management(in_drainage_line, name_lyr)

        '''Create the query expression for line features with matching records in the flat table'''
        expression_base = self.name_ID + " IN ("
        count = len(list_uniqueID)
        counter = 1
        for each_ID in list_uniqueID:
            if counter == count:
                expression_base = expression_base + str(each_ID) + ")"
            else:
                expression_base = expression_base + str(each_ID) + ", "
            counter += 1


        for each_key in self.layer_minScale_maxScale_query.keys():
            out_copy = os.path.join(path_database, "Flowline_"+each_key)
            pars = self.layer_minScale_maxScale_query[each_key]
            query = pars[2]
            expression = expression_base
            if query is not None:
                expression = expression_base + "AND " + query

            arcpy.SelectLayerByAttribute_management(name_lyr, "NEW_SELECTION", expression)
            arcpy.CopyFeatures_management(name_lyr, out_copy)
            arcpy.AddIndex_management(out_copy, self.name_ID, self.name_ID, "UNIQUE", "ASCENDING")

        return 
Example #2
Source File: arcapi_test.py    From arcapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
def testdlt(self):
        est = []
        wc = '"OBJECTID" < 11'
        lr = arcpy.management.MakeFeatureLayer(self.t_fc, "lr", wc).getOutput(0)
        # TODO: test for deleting layers won't pass even though ap.dlt works
        #print lr
        #print arcpy.Exists(lr)
        tempfc = 'in_memory\\tmp'
        if arcpy.Exists(tempfc):
            arcpy.Delete_management(tempfc)
        tmpfc = arcpy.CopyFeatures_management(lr, tempfc).getOutput(0)
        tempshp = arcpy.CreateScratchName('tmp.dbf', workspace='c:\\temp').replace('.dbf', '.shp')
        fc = arcpy.CopyFeatures_management(tmpfc, tempshp).getOutput(0)
        ap.dlt(lr)
        est.append(ap.dlt(tmpfc))
        est.append(ap.dlt(fc))
        est.append(ap.dlt('this does not exist'))
        self.assertEquals(est, [True, True, False])
        pass 
Example #3
Source File: arcapi_test.py    From arcapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
def testadd_fields_from_table(self):
        fc = os.path.join(self.testing_gdb, 'Illinois')
        copy = fc + '_copy'
        if arcpy.Exists(copy):
            arcpy.Delete_management(copy)
        arcpy.CopyFeatures_management(fc, copy)
        flds = ['POP1990', 'POP2000']
        tab = fc = os.path.join(self.testing_gdb, 'Illinois_county_info')
        ap.add_fields_from_table(copy, tab, flds)
        est = [f.name for f in arcpy.ListFields(copy)]
        try:
            arcpy.Delete_management(copy)
        except: pass
        for f in flds:
            self.assertTrue(f in est)
        pass 
Example #4
Source File: arcapi_test.py    From arcapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
def testjoin_using_dict(self):
        if arcpy.Exists(r'in_memory\copy'):
            arcpy.Delete_management(r'in_memory\copy')
        fc = os.path.join(self.testing_gdb, 'Illinois')
        copy = fc + '_copy'
        if arcpy.Exists(copy):
            arcpy.Delete_management(copy)
        arcpy.CopyFeatures_management(fc, copy)
        flds = ['POP1990', 'POP2000']
        tab = fc = os.path.join(self.testing_gdb, 'Illinois_county_info')
        ap.join_using_dict(copy, 'CNTY_FIPS', tab, 'CNTY_FIPS', flds)
        est = [f.name for f in arcpy.ListFields(copy)]
        try:
            arcpy.Delete_management(copy)
        except: pass
        for f in flds:
            self.assertTrue(f in est)
        pass 
Example #5
Source File: arcapi_test.py    From arcapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
def testconcatenate_fields(self):
        if arcpy.Exists(r'in_memory\copy'):
            arcpy.Delete_management(r'in_memory\copy')
        fc = os.path.join(self.testing_gdb, 'Illinois')
        copy = fc + '_copy'
        if arcpy.Exists(copy):
            arcpy.Delete_management(copy)
        arcpy.CopyFeatures_management(fc, copy)
        ap.concatenate_fields(copy, 'FULL', 75, ['NAME', 'STATE_NAME'], ' County, ')
        obs = 'Jo Daviess County, Illinois'
        with arcpy.da.SearchCursor(copy, 'FULL') as rows:
            est = rows.next()[0]
        del rows
        try:
            arcpy.Delete_management(copy)
        except: pass
        self.assertEqual(est, obs)
        pass 
Example #6
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
def to_points(tbl, out_fc, xcol, ycol, sr, zcol='#', w=''):
    """Convert table to point feature class, return path to the feature class.

    Required:
    tbl -- input table or table view
    out_fc -- path to output feature class
    xcol -- name of a column in tbl that stores x coordinates
    ycol -- name of a column in tbl that stores y coordinates
    sr -- spatial reference for out_fc
        sr can be either arcpy.SpatialReference object or a well known id as int

    Optional:
    zcol -- name of a column in tbl that stores y coordinates, default is '#'
    w -- where clause to limit the rows of tbl considered, default is ''

    Example:
    >>> t = 'c:\\foo\\bar.shp'
    >>> o = 'c:\\foo\\bar_pts.shp'
    >>> table_to_points(t, o, "XC", "YC", 4326, zcol='#', w='"FID" < 10')
    >>> table_to_points(t, o, "XC", "YC", arcpy.SpatialReference(27700))
    >>> table_to_points(t, o, "XC", "YC", arcpy.describe(tbl).spatialReference)
    """
    lrnm = tstamp('lr', '%m%d%H%M%S', '')
    if type(sr) != arcpy.SpatialReference:
        sr = arcpy.SpatialReference(sr)
    lr = arcpy.MakeXYEventLayer_management(tbl, xcol, ycol, lrnm, sr, zcol).getOutput(0)
    if str(w) not in ('', '*'):
        arcpy.SelectLayerByAttribute_management(lr, "NEW_SELECTION", w)
    out_fc = arcpy.CopyFeatures_management(lr, out_fc).getOutput(0)
    dlt(lr)
    return (arcpy.Describe(out_fc).catalogPath) 
Example #7
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
def make_poly_from_extent(ext, sr):
    """Make an arcpy polygon object from an input extent object.,Returns
    a polygon geometry object.

    Required:
    ext -- extent object
    sr -- spatial reference

    Example
    >>> ext = arcpy.Describe(fc).extent
    >>> sr = 4326  #WKID for WGS 84
    >>> poly = make_poly_from_extent(ext, sr)
    >>> arcpy.CopyFeatures_management(poly, r'C:\Temp\Project_boundary.shp')
    """
    array = arcpy.Array()
    array.add(ext.lowerLeft)
    array.add(ext.lowerRight)
    array.add(ext.upperRight)
    array.add(ext.upperLeft)
    array.add(ext.lowerLeft)
    return arcpy.Polygon(array, sr) 
Example #8
Source File: CreateWeightTableFromECMWFRunoff.py    From python-toolbox-for-rapid with Apache License 2.0 5 votes vote down vote up
def createPolygon(self, lat, lon, extent, out_polygons, scratchWorkspace):
        """Create a Thiessen polygon feature class from numpy.ndarray lat and lon
           Each polygon represents the area described by the center point
        """
        buffer = 2 * max(abs(lat[0]-lat[1]),abs(lon[0] - lon[1]))
        # Extract the lat and lon within buffered extent (buffer with 2* interval degree)
        lat0 = lat[(lat >= (extent.YMin - buffer)) & (lat <= (extent.YMax + buffer))]
        lon0 = lon[(lon >= (extent.XMin - buffer)) & (lon <= (extent.XMax + buffer))]
        # Spatial reference: GCS_WGS_1984
        sr = arcpy.SpatialReference(4326)

        # Create a list of geographic coordinate pairs
        pointGeometryList = []
        for i in range(len(lon0)):
            for j in range(len(lat0)):
                point = arcpy.Point()
                point.X = float(lon0[i])
                point.Y = float(lat0[j])
                pointGeometry = arcpy.PointGeometry(point, sr)
                pointGeometryList.append(pointGeometry)

        # Create a point feature class with longitude in Point_X, latitude in Point_Y
        out_points = os.path.join(scratchWorkspace, 'points_subset')
        result2 = arcpy.CopyFeatures_management(pointGeometryList, out_points)
        out_points = result2.getOutput(0)
        arcpy.AddGeometryAttributes_management(out_points, 'POINT_X_Y_Z_M')

        # Create Thiessen polygon based on the point feature
        result3 = arcpy.CreateThiessenPolygons_analysis(out_points, out_polygons, 'ALL')
        out_polygons = result3.getOutput(0)

        return out_points, out_polygons 
Example #9
Source File: CopyDataToServer.py    From python-toolbox-for-rapid with Apache License 2.0 5 votes vote down vote up
def execute(self, parameters, messages):
        """The source code of the tool."""
        arcpy.env.overwriteOutput = True

        in_data = parameters[0].value
        in_workspace_server = parameters[1].valueAsText

        for row in in_data:
            data = row[0]
            name = os.path.basename(str(data))
            if "Discharge_Table" in name:
                outTable = os.path.join(in_workspace_server, name)
                # Copy discharge table
                arcpy.CopyRows_management(data, outTable, '#')
                # Add attribute index to the discharge table
                arcpy.AddIndex_management(outTable, self.fields_oi[1], self.fields_oi[1])
                arcpy.AddIndex_management(outTable, self.fields_oi[3], self.fields_oi[3])
            elif "Flowline_" in name:
                outFlowline = os.path.join(in_workspace_server, name)
                # Copy flowline feature class
                arcpy.CopyFeatures_management(data, outFlowline)
                # Add attribute index to the flowline feature class
                arcpy.AddIndex_management(outFlowline, self.name_ID, self.name_ID, "UNIQUE", "ASCENDING")
            else:
                arcpy.AddMessage("{0} is not copied due to incorrect name".format(name))


        return 
Example #10
Source File: spatial.py    From ArcREST with Apache License 2.0 5 votes vote down vote up
def merge_feature_class(merges, out_fc, cleanUp=True):
    """ merges featureclass into a single feature class """
    if arcpyFound == False:
        raise Exception("ArcPy is required to use this function")
    if cleanUp == False:
        if len(merges) == 0:
            return None
        elif len(merges) == 1:
            desc = arcpy.Describe(merges[0])
            if hasattr(desc, 'shapeFieldName'):
                return arcpy.CopyFeatures_management(merges[0], out_fc)[0]
            else:
                return arcpy.CopyRows_management(merges[0], out_fc)[0]
        else:
            return arcpy.Merge_management(inputs=merges,
                                          output=out_fc)[0]
    else:
        if len(merges) == 0:
            return None
        elif len(merges) == 1:
            desc = arcpy.Describe(merges[0])
            if hasattr(desc, 'shapeFieldName'):
                merged = arcpy.CopyFeatures_management(merges[0], out_fc)[0]
            else:
                merged = arcpy.CopyRows_management(merges[0], out_fc)[0]
        else:
            merged = arcpy.Merge_management(inputs=merges,
                                        output=out_fc)[0]
        for m in merges:
            arcpy.Delete_management(m)
            del m
        return merged
#---------------------------------------------------------------------- 
Example #11
Source File: DataServicePillager.py    From DataPillager with MIT License 5 votes vote down vote up
def combine_data(fc_list, output_fc):
    """ :param fc_list: array of featureclass paths as strings
        :param output_fc: path to output dataset
        Combine the downloaded datafiles into one
        fastest approach is to use cursor
    """
    if len(fc_list) == 1:
        arcpy.Copy_management(fc_list[0], output_fc)
        output_msg("Created {0}".format(output_fc))
    else:
        for fc in fc_list:
            if fc_list.index(fc) == 0:
                # append to first dataset. much faster
                output_msg("Prepping yer first dataset {0}".format(fc))
                if arcpy.Exists(output_fc):
                    output_msg("Avast! {0} exists, deleting...".format(output_fc), severity=1)
                    arcpy.Delete_management(output_fc)
                
                arcpy.Copy_management(fc, output_fc)  # create dataset to append to
                output_msg("Created {0}".format(output_fc))

                fieldlist = []
                #fieldlist = ["SHAPE@"]
                fields = arcpy.ListFields(output_fc)
                for field in fields:
                    if field.name.lower() == u'shape':
                        fieldlist.insert(0, "SHAPE@") # add shape token to start
                    else:
                        fieldlist.append(field.name)
                #fields = [field.name for field in arcpy.ListFields(output_fc) if field.name.lower() not in [u'shape']]
                #fieldlist.extend(fields)
                ##arcpy.CopyFeatures_management(output_fc, fc) # duplicate first one so delete later doesn't fail
                insert_rows = arcpy.da.InsertCursor(output_fc, fieldlist)
            else:
                search_rows = arcpy.da.SearchCursor(fc, fieldlist) # append to first dataset
                for row in search_rows:
                    insert_rows.insertRow(row)
                del row, search_rows
                output_msg("Appended {0}...".format(fc))
        del insert_rows 
Example #12
Source File: arcapi_test.py    From arcapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testrename_col(self):
        import arcpy
        import tempfile
        owo = arcpy.env.overwriteOutput
        arcpy.env.overwriteOutput = True
        tmpfc = os.path.join(tempfile.gettempdir(), "tmp")
        tmpfc = arcpy.CopyFeatures_management(self.t_fc, tmpfc).getOutput(0)
        est = ap.rename_col(tmpfc, "ABBREV", "ABBREVIATION")
        obs = "ABBREVIATI"
        arcpy.Delete_management(tmpfc)
        arcpy.env.overwriteOutput = owo
        self.assertEqual(est, obs)
        pass