Hi all
In my python code scripting, some time I used some function to do analysis on shapefile. Those function need to specify the .shp in the filename like arcpy.Rename_management(output+'.shp', filename). When I used files in geodatabase, my script crashed.
I am wondering how I can handle this problem?
I want just specify that my script loop over lot of files.
Thanks in advance
Just copy and paste your code into the post as plain text; forget the syntax highlighting.
import arcpy
import os
import sys
import tkMessageBox
from arcpy import env
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd,"Layers")[0]
# Set all the parameters
choice = arcpy.GetParameterAsText(0)
workspace = arcpy.GetParameterAsText(1)
fClass = arcpy.GetParameterAsText(2)
addFields = arcpy.GetParameterAsText(3)
reStruct = arcpy.GetParameterAsText(4)
addMiss = arcpy.GetParameterAsText(5)
delShp = arcpy.GetParameterAsText(6)
# Set fields parameters
namesFields =["SciName","CommName_E","CommName_F","Population","SpeciesID","SiteID","SiteName","CHApproach",\
"CHMethod","Region","ProvTerr","LandTenure","UTMZone","Easting","Northing","Latitude","Longitude",\
"Area_ha","Comments","DateEdited"]
typeF = ["STRING","STRING","STRING","STRING","SHORT","STRING","STRING","STRING","STRING","STRING","STRING",\
"STRING","SHORT","DOUBLE","DOUBLE","DOUBLE","DOUBLE","DOUBLE","STRING","DATE"]
lenghF = [100,100,100,100,"",125,125,50,75,75,75,75,"","","","","","",250,""]
labelS=["Scientific","Common","Nom","Population","COSEWIC","Site ID","Site Name",\
"Approach","Method","Region","Province","Tenure","UTM","Easting",\
"Northing","Latitude","Longitude","Area","Comments","Date"]
# Set the workspace
env.workspace = workspace
arcpy.env.overwriteOutput = True
# Verify the single feature class and the selected choice
if (choice == "false" and fClass == ""):
arcpy.AddMessage("----------------------------------------------------------------")
arcpy.AddMessage("Workspace/Single feature class check box is unselect.\n You have to select a single feature class or click to select the check box")
arcpy.AddMessage("----------------------------------------------------------------")
sys.exit()
#-------------------------------------------------------------------------------------------
# Rename function
def rename_fields(table, out_table, new_name_by_old_name):
existing_field_names = [field.name for field in arcpy.ListFields(table)]
field_mappings = arcpy.FieldMappings()
field_mappings.addTable(table)
for old_field_name, new_field_name in new_name_by_old_name.iteritems():
if old_field_name not in existing_field_names:
message = "Field: {0} not in {1}".format(old_field_name, table)
raise Exception(message)
mapping_index = field_mappings.findFieldMapIndex(old_field_name)
field_map = field_mappings.fieldMappings[mapping_index]
output_field = field_map.outputField
output_field.name = new_field_name
output_field.aliasName = new_field_name
field_map.outputField = output_field
field_mappings.replaceFieldMap(mapping_index, field_map)
# use merge with single input just to use new field_mappings
arcpy.Merge_management(table, out_table, field_mappings)
return out_table
# Reorder function
def reorder_fields(table, out_table, field_order, add_missing=addMiss):
existing_fields = arcpy.ListFields(table)
existing_field_names = [field.name for field in existing_fields]
existing_mapping = arcpy.FieldMappings()
existing_mapping.addTable(table)
new_mapping = arcpy.FieldMappings()
def add_mapping(field_name):
mapping_index = existing_mapping.findFieldMapIndex(field_name)
# required fields (OBJECTID, etc) will not be in existing mappings
# they are added automatically
if mapping_index != -1:
field_map = existing_mapping.fieldMappings[mapping_index]
new_mapping.addFieldMap(field_map)
# add user fields from field_order
for field_name in field_order:
if field_name not in existing_field_names:
raise Exception("Field: {0} not in {1}".format(field_name, table))
add_mapping(field_name)
# add missing fields at end
if add_missing:
missing_fields = [f for f in existing_field_names if f not in field_order]
for field_name in missing_fields:
add_mapping(field_name)
# use merge with single input just to use new field_mappings
arcpy.Merge_management(table, out_table, new_mapping)
return out_table
#-------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------
# Processing
#-------------------------------------------------------------------------------------------
# Target the selected fields
namesA = []
names = []
namesA= addFields.split(";")
for i in range (0,len(namesA)):
for j in range (0,len(labelS)):
if labelS
names.append(namesFields
#-------------------------------------------------------------------------------------------
arcpy.AddMessage("List of fields to add = ")
for i in range(0, len(names)):
arcpy.AddMessage(names)
#-------------------------------------------------------------------------------------------
if choice == "true":
listCH_fc = []
listCH_fc = arcpy.ListFeatureClasses()
else:
listCH_fc = []
listCH_fc.append(fClass)
for fc in listCH_fc:
# Add fields
fieldList = arcpy.ListFields(fc)
nameList = []
nameListO = []
new_name_by_old_name={}
for lst in fieldList:
nameList.append(lst.name.lower())
nameListO.append(lst.name)
for i in range (0,len(names)):
if not names.lower() in nameList:
arcpy.AddField_management(fc,names,typeF,"", "", lenghF, names, "NULLABLE")
else:
indexes = [k for k, l in enumerate(nameList) if names.lower() in l]
old = nameListO[indexes[0]]
new = names
arcpy.AddMessage(old)
arcpy.AddMessage(new)
new_name_by_old_name.update({old:new})
arcpy.AddMessage("New_name and old name for the fields to rename:")
arcpy.AddMessage(new_name_by_old_name)
arcpy.env.overwriteOutput = True
output = str(fc).replace('.shp','')+"_AddRenameF"
rename_fields(fc, output, new_name_by_old_name)
if reStruct == "true":
fieldListRE = arcpy.ListFields(output+".shp")
nameListORE = []
for lstRE in fieldListRE:
nameListORE.append(lstRE.name)
nameListORE_F = []
for ii in range(0,len(namesFields)):
for jj in range (0, len(nameListORE)):
if nameListORE[jj] == namesFields[ii]:
nameListORE_F.append(nameListORE[jj])
output_R = output.replace('.shp','')+"_RF_ReorderF"
reorder_fields(output+".shp", output_R, nameListORE_F)
# Delete existing feature class (fc) and rename generated feature class
filename = fc
arcpy.Delete_management(filename)
if choice == "false":
filename=os.path.basename(str(fc)).rstrip(os.path.splitext(str(fc))[1])
filename = filename.replace('.shp','')
else:
filename = str(fc).replace('.shp','')
arcpy.Rename_management(output_R+".shp", filename + ".shp")
# add layer to mxd
filename=os.path.basename(str(filename)).rstrip(os.path.splitext(str(filename))[1])
if arcpy.Exists(filename):
arcpy.Delete_management(filename)
arcpy.MakeFeatureLayer_management(filename+".shp", filename.replace('.shp',''))
layer = arcpy.mapping.Layer(filename.replace('.shp',''))
layer.visible = False
arcpy.mapping.AddLayer(df, layer, "BOTTOM")
if (delShp == "true" and reStruct == "true"):
filename=os.path.basename(str(output)).rstrip(os.path.splitext(str(output))[1])
arcpy.Delete_management(filename + ".shp")
else:
# add layer to mxd
filename=os.path.basename(str(output)).rstrip(os.path.splitext(str(output))[1])
arcpy.AddMessage(filename)
if arcpy.Exists(filename):
arcpy.Delete_management(filename)
arcpy.MakeFeatureLayer_management(filename+".shp", filename.replace('.shp',''))
layer = arcpy.mapping.Layer(filename.replace('.shp',''))
layer.visible = False
arcpy.mapping.AddLayer(df, layer, "BOTTOM")
I believe Owain Catton mentioned that you are trying to append ".shp" to the name which is invalid for a geodatabase. .shp is reserved for Shape files....
So there may be a question on whether or not you are using Geodatabase layers or layers derived from shape files?