Select to view content in your preferred language

ArcPy script tool overwriting content

302
5
Jump to solution
3 weeks ago
Labels (2)
AliciaMcMurchie1
Regular Contributor
def main ():

    #importArcPy
    import arcpy
    #import os
    import os
    #import module
    import arcpy.da

    #set variables
    raw_input = arcpy.GetParameterAsText(0)
    output_GDB = arcpy.GetParameterAsText(1)
    var_shape = os.path.join(output_GDB,
                            os.path.splitext(os.path.basename(raw_input))[0])
    service_change = arcpy.GetParameterAsText(2)
    effective_date = arcpy.GetParameterAsText(3)

    service_change_param = "'" + service_change + "'"
    effective_date_param = "'" + effective_date + "'"

    if arcpy.Exists(var_shape):
        arcpy.AddError("A feature class using the name var_shape already exists in the output Geodatabase. Exiting tool.")
        sys.exit(0)

    else:
        try:

            def export ():
            #will need to set input and output as a parameters. Output, when set as a parameter, will be the SAME as the environment workspace parameter
                
                arcpy.conversion.FeatureClassToGeodatabase(raw_input,output_GDB)

            def prep ():

                #set up workspace
                #this will need to be a parameter - the SAME as the output GDB in the export function
                arcpy.env.workspace = output_GDB

                #add new field to shapefile
                arcpy.management.AddField(
                    in_table=var_shape,
                    field_name="ROUTE",
                    field_type="LONG",
                    field_precision=None,
                    field_scale=None,
                    field_length=None,
                    field_alias="",
                    field_is_nullable="NULLABLE",
                    field_is_required="NON_REQUIRED",
                    field_domain=""
                )

                #set field variables
                var_shape_fields = ['VAR_ROUTE','ROUTE']

                #use Update Cursors

                with arcpy.da.UpdateCursor(var_shape, var_shape_fields) as cursor:
                    #for each row, evaluate VAR_ROUTE string and plan to update ROUTE with route number as integer
                    for row in cursor:
                        row[1] = int(row[0])
                        #Update each row in table
                        cursor.updateRow(row)
                arcpy.AddMessage("prep done")

            def deletefield ():
            #delete the VAR_ROUTE field that was in Text data type
                
                    arcpy.management.DeleteField(
                    in_table=var_shape,
                    drop_field="VAR_ROUTE",
                    method="DELETE_FIELDS"
                )


            def new_fields():
            #add new field for dates
                arcpy.management.AddField(
                    in_table=var_shape,
                    field_name="SERVICE_CHANGE",
                    field_type="DATE",
                    field_precision=None,
                    field_scale=None,
                    field_length=None,
                    field_alias="",
                    field_is_nullable="NULLABLE",
                    field_is_required="NON_REQUIRED",
                    field_domain=""
                )
                arcpy.management.AddField(
                    in_table=var_shape,
                    field_name="EFFECTIVE_DATE_START",
                    field_type="DATE",
                    field_precision=None,
                    field_scale=None,
                    field_length=None,
                    field_alias="",
                    field_is_nullable="NULLABLE",
                    field_is_required="NON_REQUIRED",
                    field_domain=""
                )
                arcpy.AddMessage("new_field done")

            def add_dates():
            #Expression will need to be set as a parameter
                arcpy.management.CalculateField(
                    in_table=var_shape,
                    field="SERVICE_CHANGE",
                    expression=service_change_param,
                    expression_type="SQL",
                    code_block="",
                    field_type="TEXT",
                    enforce_domains="NO_ENFORCE_DOMAINS"
                )

                arcpy.management.CalculateField(
                    in_table=var_shape,
                    field="EFFECTIVE_DATE_START",
                    expression=effective_date_param,
                    expression_type="SQL",
                    code_block="",
                    field_type="TEXT",
                    enforce_domains="NO_ENFORCE_DOMAINS"
                )

                arcpy.AddMessage("dates added")
                
        except Exception as exception:
            arcpy.AddError(exception)

        finally:
            arcpy.AddMessage("routes script completed")

        export()
        prep()
        deletefield()
        new_fields()
        add_dates()

main()

I'm struggling to write an ArcPy script tool that exports a shapefile to an Enterprise GDB and then runs several geoprocessing steps on it. The input shape file is named "var_shape.shp". The script tool runs successfully, but if I rename the output feature class in the Enterprise GDB to something like var_shape_00 and then rerun the tool, var_shape_00 gets overwritten by the next export. What can I do to avoid this? Here's the top of the script tool, where things go wrong:overwritten.png

0 Kudos
1 Solution

Accepted Solutions
DanPatterson
MVP Esteemed Contributor

Rename (Data Management)—ArcGIS Pro | Documentation

doesn't make a backup copy, and it list the things it does

If you are trying to preserve a copy, then use Copy or Copy Features depending on the data source and destinations types

Copy (Data Management)—ArcGIS Pro | Documentation

Copy Features (Data Management)—ArcGIS Pro | Documentation


... sort of retired...

View solution in original post

0 Kudos
5 Replies
DavidPike
MVP Notable Contributor

Nothing immediately obvious to me, If there's an operation to clear out data from the GDB then I can't see it.

I think you need to share your full code and also not a screenshot, it's not very helpful. Code formatting ... the Community Version - Esri Community

0 Kudos
AliciaMcMurchie1
Regular Contributor

Thanks, I added that in. Obviously, I'm not very familiar with ArcPy, or Python in general. 

0 Kudos
AliciaMcMurchie1
Regular Contributor

I tried using  arcpy.env.overwriteOutput=False at the beginning of the script. I thought it resolved the issue at first, but it appears it didn't.

0 Kudos
DanPatterson
MVP Esteemed Contributor

Rename (Data Management)—ArcGIS Pro | Documentation

doesn't make a backup copy, and it list the things it does

If you are trying to preserve a copy, then use Copy or Copy Features depending on the data source and destinations types

Copy (Data Management)—ArcGIS Pro | Documentation

Copy Features (Data Management)—ArcGIS Pro | Documentation


... sort of retired...
0 Kudos
AliciaMcMurchie1
Regular Contributor

"Rename" has saved the day! A backup copy isn't needed, so this script has proven successful: 

def main ():

    #importArcPy
    import arcpy
    #import os
    import os
    #import module
    import arcpy.da
    arcpy.env.overwriteOutput=False

    #set variables
    raw_input = arcpy.GetParameterAsText(0)
    output_GDB = arcpy.GetParameterAsText(1)
    service_change = arcpy.GetParameterAsText(2)
    effective_date = arcpy.GetParameterAsText(3)
    new_name = arcpy.GetParameterAsText(4)
    route_file = os.path.join(output_GDB,
                        os.path.splitext(os.path.basename(raw_input))[0])
    new_file = os.path.join(output_GDB,
                        os.path.splitext(new_name)[0])

    service_change_param = "'" + service_change + "'"
    effective_date_param = "'" + effective_date + "'"

    if arcpy.Exists(route_file):
        arcpy.AddError("A feature class using the name var_shape already exists in the output Geodatabase. Exiting tool.")
        sys.exit(0)

    elif arcpy.Exists(new_file):
        arcpy.AddError("A feature class using the new name already exists in the output Geodatabase. Exiting tool.")
        sys.exit(0)

    else:
        try:

            def export ():
            #will need to set input and output as a parameters. Output, when set as a parameter, will be the SAME as the environment workspace parameter
                arcpy.env.overwriteOutput=False
                arcpy.conversion.FeatureClassToGeodatabase(raw_input,output_GDB)
                arcpy.management.Rename(route_file, new_name)

            def prep ():

                #set up workspace
                #this will need to be a parameter - the SAME as the output GDB in the export function
                arcpy.env.workspace = output_GDB
                arcpy.management.ClearWorkspaceCache(output_GDB)
                arcpy.env.overwriteOutput=False
                #add new field to shapefile
                arcpy.management.AddField(
                    in_table=new_file,
                    field_name="ROUTE",
                    field_type="LONG",
                    field_precision=None,
                    field_scale=None,
                    field_length=None,
                    field_alias="",
                    field_is_nullable="NULLABLE",
                    field_is_required="NON_REQUIRED",
                    field_domain=""
                )

                #set field variables
                new_file_fields = ['VAR_ROUTE','ROUTE']

                #use Update Cursors

                with arcpy.da.UpdateCursor(new_file, new_file_fields) as cursor:
                    #for each row, evaluate VAR_ROUTE string and plan to update ROUTE with route number as integer
                    for row in cursor:
                        row[1] = int(row[0])
                        #Update each row in table
                        cursor.updateRow(row)
                arcpy.AddMessage("prep done")

            def deletefield ():
            #delete the VAR_ROUTE field that was in Text data type
                
                    arcpy.management.DeleteField(
                    in_table=new_file,
                    drop_field="VAR_ROUTE",
                    method="DELETE_FIELDS"
                )


            def new_fields():
            #add new field for dates
                arcpy.management.AddField(
                    in_table=new_file,
                    field_name="SERVICE_CHANGE",
                    field_type="DATE",
                    field_precision=None,
                    field_scale=None,
                    field_length=None,
                    field_alias="",
                    field_is_nullable="NULLABLE",
                    field_is_required="NON_REQUIRED",
                    field_domain=""
                )
                arcpy.management.AddField(
                    in_table=new_file,
                    field_name="EFFECTIVE_DATE_START",
                    field_type="DATE",
                    field_precision=None,
                    field_scale=None,
                    field_length=None,
                    field_alias="",
                    field_is_nullable="NULLABLE",
                    field_is_required="NON_REQUIRED",
                    field_domain=""
                )
                arcpy.AddMessage("new_field done")

            def add_dates():
            #Expression will need to be set as a parameter
                arcpy.management.CalculateField(
                    in_table=new_file,
                    field="SERVICE_CHANGE",
                    expression=service_change_param,
                    expression_type="SQL",
                    code_block="",
                    field_type="TEXT",
                    enforce_domains="NO_ENFORCE_DOMAINS"
                )

                arcpy.management.CalculateField(
                    in_table=new_file,
                    field="EFFECTIVE_DATE_START",
                    expression=effective_date_param,
                    expression_type="SQL",
                    code_block="",
                    field_type="TEXT",
                    enforce_domains="NO_ENFORCE_DOMAINS"
                )

                arcpy.AddMessage("dates added")
                
        except Exception as exception:
            arcpy.AddError(exception)

        finally:
            arcpy.AddMessage("routes script completed")

        export()
        prep()
        deletefield()
        new_fields()
        add_dates()

main()
0 Kudos