Editing shapefiles with Python

1494
4
04-01-2012 03:17 AM
CharlesGant
New Contributor III
Hello folks.  I had a post over on the general forum about how to round values using the field calculator.  I got the answer I was looking for but was referred to this board to ask a question about python. 

I have to edit a series of shapefiles (about 100).  They all have the same field labels.  I need to add a field, and then round a certain field we will call "X", to the nearest five, and populate the new field with those values.  The formula I was given was  "Round(/5.0, 0) * 5.0".  I have a some experience working with arcpy and python, however I have never used it to modify a shapefile.  Can someone help me out with the script I would use to do what I have described above so i can then write it into a loop and do the work on all my shapefiles.  I can handle the loop part.  Thanks!
Tags (2)
0 Kudos
4 Replies
NareshPai
New Contributor
It would be useful to give the forum some code to start with. You may need arcpy.AddField_management and arcpy.CalculateField_management to get started with the loop.

Naresh Pai
0 Kudos
CharlesGant
New Contributor III
Sorry about that.  Here is what I have so far.  For simplicity on the forum, I have just one shapefile in the code for now.  If I can get help with the code to do what I want on one, I can build the for loop to do the rest with the remaining shapefiles in a list.


 
# Import modules
import arcpy
import math

# Local variables:
point_shp = "R:\\Tornado Research\\test\\SfcOA.shp"


newfield = R_WsdpSfc
input = "getclass(double(!WSPD_SFC!))" #Not sure how to get the input file in this line of code
expression = "round([input]/5.0, 0) * 5.0" #Not sure if this is the correct way of doing this line

# Process: Add Field
arcpy.AddField_management(point_shp, newfield, "DOUBLE", "", "", "25", "", "NON_NULLABLE", "NON_REQUIRED", "") # Works fine

# Execute CalculateField 
arcpy.CalculateField_management(point_shp, newfield, expression, "PYTHON") #Obviously this line is broken



The "Add Field" command works just fine, I just cant figure out the "Calculate Field" segment.  Thanks Again!
0 Kudos
JakeSkinner
Esri Esteemed Contributor
Try changing your expression variable to:

expression = "round(!WSPD_SFC!/5.0, 0) * 5.0"


Since the expression is quoted as a string, it will not read 'input' as a variable.  It will read this as a string literal.
0 Kudos
CharlesGant
New Contributor III
Try changing your expression variable to:

expression = "round(!WSPD_SFC!/5.0, 0) * 5.0"


Since the expression is quoted as a string, it will not read 'input' as a variable.  It will read this as a string literal.


Wow, I dont know why I did not realize that!  I completely overlooked it.  That fixed it!  I guess sometimes when you stare at this stuff for so long, eventually you just need a new set of eyes to look it over.  Thanks Jake!
0 Kudos