[FWTools] python ogr - setField attribute error

David Fawcett david.fawcett at gmail.com
Mon Oct 23 11:35:29 EDT 2006

I am bastardizing Matt Perry's text2shp.py and running into an error.

I am taking values from a text file and building a shapefile.  The error
occurs when I try to set the value of first field of a feature.  I am not
sure what would cause this error.

Below is the shell output.  The first list printed is the column names, the
second list is the field types. The last line before the error is the column
number and the value to be inserted into that field (print colNum,

D:\datascripts>python csv2shp.py

['stn_type', 'stn_name', 'X', 'Y', 'col_meth', 'col_date', 'org_name',
', 'gnd_elev', 'uniq_id', 'tos_elev', 'bos_elev', 'comments']

[4, 4, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4]

0 Monitoring Well

Traceback (most recent call last):
  File "csv2shp.py", line 129, in ?
    f.setField(colNum, cols[colNum])
  File "C:\PROGRA~1\FWTOOL~1.5\pymod\ogr.py", line 755, in __getattr__
    raise AttributeError, name
AttributeError: setField

here is the relevant part of the script

ds = driver.CreateDataSource(outputFile)
layer = ds.CreateLayer(outputFile, geom_type=ogr.wkbPoint)

print colNames
print colTypes
#create fields
for j in range(len(colNames)):
    fd = ogr.FieldDefn(colNames[j].strip(), colTypes[j])
    fd.SetWidth(maxWidth[j] + 12)

#second pass through data file
myFile = open(inputFile, 'r')

#skip the header row
line = myFile.readline()
#read the first data row
line = myFile.readline()

while line:
    cleanline = line.replace('\n','')
    cols = cleanline.split(delimiter)

    #create the feature
    f= ogr.Feature(feature_def=layer.GetLayerDefn())

    # Fill in the attribute fields
    for colNum in range(len(cols)):
        print colNum, cols[colNum]
        f.setField(colNum, cols[colNum])         # this is line 129 where
the error is being raised

    # if there is a coordinate, use it to create a geometry
    if cols[xColNum] and cols[yColNum]:
        x = float(cols[xColNum])
        y = float(cols[yColNum])

        #create point feature
        wkt = 'POINT(%f %f)' % (x,y)
        g = ogr.CreateGeometryFromWkt(wkt)


#destroying the data source closes the output shapefile
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.maptools.org/pipermail/fwtools/attachments/20061023/ac47876f/attachment.html

More information about the FWTools mailing list