Tuesday, 18 June 2013

Batch Add Fields

Again this file has hardcoded information but could be turned into a tool for use within ArcMap.  It batch adds a field(s) to a files in a folder.

'''
BatchAddFields.py

Purpose:
  A simple demo script showing how fields can be added
  to a bunch of shapefiles in a folder. The workspace, the field and its
  type are hardcoded at present but could be converted to parameters
'''
import sys, string, os
import arcpy
arcpy.env.workspace = "C:/temp2"    #change to suit your workspace
install_dir = arcpy.GetInstallInfo()['InstallDir'].replace("
\\","/")
sub_folder = "ArcToolbox/Toolboxes/"
tbx_home = os.path.join(install_dir, sub_folder)
print "\nCurrent workspace: ", arcpy.env.workspace
arcpy.AddToolbox(tbx_home + "/Data Management Tools.tbx")
rows = arcpy.ListFeatureClasses()

for row in rows:
  try:
    name = row[:row.find('.')]
    arcpy.AddField_management(name + ".shp", "TestField", "LONG", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    print "Added field to: ", name
  except:
    print "Adding field failed.", arcpy.GetMessages()

No comments:

Post a Comment