Problem with arcpy.ListFields

5638
9
09-13-2011 09:42 AM
chriss_
New Contributor II
Hi!

I try to use the arcpy.ListFields command. It only works when I type in the name of the shape file directly. It does not work when I try to use a shapefile name from a list.
So to chekc my Code I added the print comand and it perfectly prints out the name of the shape.
Example: 'River' But the code still doesn't work. If I enter 'River' manually it works perfectly fine.

Any idea where the mistake might be?
Thanks a lot

Doesn't work:
while x <= leta:
        Listfieldx = str("'" + str(tableList)+"'")
        print Listfieldx
        fieldList = arcpy.ListFields(Listfieldx,"*","*")

I tried also fieldList = arcpy.ListFields(Listfieldx)
fieldList = arcpy.ListFields(str(Listfieldx)) etc, etc...

Does work:
while x <= leta:
        Listfieldx = str("'" + str(tableList)+"'")
        print Listfieldx
        fieldList = arcpy.ListFields('River')


Best regards
Chris
p.s. here the whole code
#Export all the field properties of each table in the Geodatabse
import arcpy
from arcpy import env

# Overwrite pre-existing files
arcpy.env.overwriteOutput = True
# Set the current workspace
#

# Set local variables
#Create a new table
try:
    geoDataBasePath = "P:/RAME/GIS/2011/Report.mdb"
    env.workspace = geoDataBasePath
    NewTable = "FieldProperties"
    arcpy.CreateTable_management(geoDataBasePath, NewTable)
        
    # For each field in the feature class, print all properties
    # Set local variables

    inFeatures = NewTable
    fieldName1="name"
    fieldName2="aliasName"
    fieldName3="baseName"
    fieldName4="domain"
    fieldName5="isNullable"
    fieldName6="precision"
    fieldName7="required"
    fieldName8="scale"
    fieldName9="type"
    fieldName10="length"
    fieldName11="editable"
    fieldName12="FC"
    fieldLength=255

    # Execute AddField new fields
    arcpy.AddField_management(inFeatures, fieldName1, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName2, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName3, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName4, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName5, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName6, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName7, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName8, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName9, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName10, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName11, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName12, "TEXT", "", "", fieldLength)
    
    #List all tables in the Geodatabase
    tableList = arcpy.ListTables()
    for table in tableList:
        print table
        
    #how many tables are there
    leta = len(tableList)
    print leta
    x=0
    #loop through all tables
    while x <= leta:
        Listfieldx = str("'" + str(tableList)+"'")
        print Listfieldx
        fieldList = arcpy.ListFields(Listfieldx,"*","*")
        print str(fieldList)
        for field in fieldList:
            print 1
            NewList=[]
            fc=str(tableList)
            print fc
            NewList.extend ([str(fc),str(field.name),str(field.aliasName),str(field.baseName),str(field.domain),str(field.isNullable),str(field.precision),str(field.required),str(field.scale), str(field.type),str(field.length),str(field.editable)]) 
            print NewList
            cursor = arcpy.InsertCursor(fc)
            print 2
            row = cursor.newRow()
            row.FC=NewList[11]
            row.name = NewList[0]
            row.aliasName = NewList[1]
            row.baseName = NewList[2]
            row.domain = NewList[3]
            row.isNullable = NewList[4]
            row.precision = NewList[5]
            row.required = NewList[6]
            row.scale = NewList[7]
            row.type = NewList[8]
            row.length = NewList[9]
            row.editable = NewList[10]
            print 3
            cursor.insertRow(row)
            del NewList
            x=x+1
            del row
            print 99
    del cursor
    del NewList
except:
    print "\nError!\n"
    del row
    del cursor
    del NewList


 

Tags (2)
0 Kudos
9 Replies
MathewCoyle
Frequent Contributor
Nevermind, didn't see some of your other comments... Try the below, your code seems a little needlessly complex for the operation you are doing. Unless I am missing something.

Should be as simple as.
    tableList = arcpy.ListTables()
    for table in tableList:
        fieldList = arcpy.ListFields(table)
        for field in fieldList:
0 Kudos
JakeSkinner
Esri Esteemed Contributor
You will not need to add quotes to each item in the list.  Python will already read it as a string.  Ex:

tableList = arcpy.ListTables()
for table in tableList:
    print table
        
# how many tables are there
leta = len(tableList)
print leta
x=0

# loop through all tables
while x < leta:
    Listfieldx = tableList
    fieldList = arcpy.ListFields(Listfieldx,"*","*")
    for field in fieldList:
        print field.name
    x += 1
0 Kudos
JamesHood
Occasional Contributor
From the ESRI arcpy.listfields online help:
import arcpy
from arcpy import env

# Set the current workspace
#
env.workspace = "C:/Data/Municipal.gdb"

# For each field in the Hospitals feature class, print 
#  the field name, type, and length.
fieldList = arcpy.ListFields("Hospitals")

for field in fieldList:
    print "%s is a type of %s with a length of %i" % (field.name, field.type, field.length) 


I don't know what you are trying to accomplish with the Asterisks ** inside your fieldlist, but if you delete them I figure it should work.
0 Kudos
chriss_
New Contributor II
Hi!
Thanks to all of you !
I finally finished it today. I copied the lines of Mathew, but I discovered that my original problem was that I choose an reserved field name for a field i added. ArcView changed it and add a "_" which I didn't realize. So now it is working perfectly fine.
So anybody who is interested in a tool creating a table with all table field properties of a geodatabase fell free to try it.

Best regards again
Chris

# Export all the field properties of each table in the Geodatabse to a new table
# in the same Geodatabase. If the table already exists the old one will be
# overwritten. If a problem occurs a message will appear in the python window, so
# check the window before closing.
import arcpy
from arcpy import env

# Overwrite pre-existing files
arcpy.env.overwriteOutput = True

# Get input information. Target Geodatabase and Name of the New table containing
# the Table field properties.
geoDataBasePath=arcpy.GetParameterAsText(0)
NewTable=arcpy.GetParameterAsText(1)
# Set the current workspace
# Create a new table

try:
    env.workspace = geoDataBasePath
    arcpy.CreateTable_management(geoDataBasePath, NewTable)
        
    # Naming the fields of the outputtable

    inFeatures = NewTable
    fieldName1="field_name"
    fieldName2="aliasName_"
    fieldName3="baseName_"
    fieldName4="domain_"
    fieldName5="isNullabl_"
    fieldName6="precision_"
    fieldName7="required_"
    fieldName8="scale_"
    fieldName9="type_"
    fieldName10="length_"
    fieldName11="editable_"
    fieldName12="Table_Name"
    fieldLength=255

    # Execute AddField new fields. All fields are set as text even if they contain numbers.
    arcpy.AddField_management(inFeatures, fieldName12, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName1, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName2, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName3, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName4, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName5, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName6, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName7, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName8, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName9, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName10, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName11, "TEXT", "", "", fieldLength)
    
    #List all tables in the Geodatabase
    
    tableList = arcpy.ListTables()
    x=0
    # For all tables list all fields
    for table in tableList:
        try:
            fieldList = arcpy.ListFields(table)
            for field in fieldList:
                #Get the name of the current table
                nametable=str(tableList)
                #make a new list and add the name of the table and the properties
                #of each field to the list
                NewList=[]
                NewList.extend ([str(field.name),str(field.aliasName),str(field.baseName),str(field.domain),str(field.isNullable),str(field.precision),str(field.required),str(field.scale), str(field.type),str(field.length),str(field.editable), nametable]) 
                #Use an insert cursor to add new rows with the field properties
                cursor = arcpy.InsertCursor(NewTable)
                row = cursor.newRow()
                row.field_name = NewList[0]
                row.aliasName_ = NewList[1]
                row.baseName_ = NewList[2]
                row.domain_ = NewList[3]
                row.isNullabl_=NewList[4]
                row.precision_ = NewList[5]
                row.required_ = NewList[6]
                row.scale_ = NewList[7]
                row.type_ = NewList[8]
                row.length_ = NewList[9]
                row.editable_ = NewList[10]
                row.Table_Name = NewList[11]
                cursor.insertRow(row)
            x=x+1
        #add warning message in the python window if a problem with the table appears.
        #Even a problem is reported the output is normally fine. But check to make sure.
        except:
            print "The crazy clown says there is a problem with table ", nametable, ". Check the results for this table."
       
except:
    print "\nError!\n"
del row
del cursor
del NewList


 

0 Kudos
StacyRendall1
Occasional Contributor III
From the ESRI arcpy.listfields online help:
import arcpy
from arcpy import env

# Set the current workspace
#
env.workspace = "C:/Data/Municipal.gdb"

# For each field in the Hospitals feature class, print 
#  the field name, type, and length.
fieldList = arcpy.ListFields("Hospitals")

for field in fieldList:
    print "%s is a type of %s with a length of %i" % (field.name, field.type, field.length) 


I don't know what you are trying to accomplish with the Asterisks ** inside your fieldlist, but if you delete them I figure it should work.


James, it is in quotes in the example because the field is being explicitly specified when the function is called, as opposed to using a variable... I.e. (when the feature is Hospitals😞
a = arcpy.ListFields("Hospitals")

is the same as:
feature = 'Hospitals'
a = arcpy.ListFields(feature) #no quote marks - feature is a variable

which is the same as:
feature = arcpy.GetParamaterAsText(0)
a = arcpy.ListFields(feature) #no quote marks - feature is, once again, a variable


Asterisks - I can't explain fully, the ESRI guys seem to love them, but it will default to them anyway - they are wildcards, so in this case the first one means "return all values" and the second means "return all field types".
0 Kudos
MarcNakleh
New Contributor III
Asteriskes can also be used as a wildcard in arcpy's List methods (ex. ListFields, ListFeatureClasses, ListDatasets) to expand your searches For example, arcpy.ListFields('line*') will return any field that starts by "line". Also useful if you're not too sure whether you're in a feature class or a shapefile. For example, you can use arcpy.ListFeatureClasses('Hospital*') to return a feature class named 'Hospital' but also 'Hospital.shp'.

Chris: Thanks for the code! I'm actually thinking of implementing something similar as a kind of value printer for tables. A couple of quick thoughts:

1) Python usually encourages programmers to use very targeted try...except calls. Read up on exception handling on this page. For example, your main try...except encapsulates the entire program, and will catch (and hide) all errors, even errors you might not have expected in your code itself! You could wrap only the sections that might explode (like the Create Table) in exception handlers, and even try to catch specific errors (ESRI favours catching arcpy.ExecuteError and printing them out with arcpy.GetMessages())

2) You might also want to look at finding ways to represent repetitive code by some of Python's built-in data structures, like dictionaries and lists (explained more here.)
For example, you could replace the following:

    fieldName1="field_name"
    fieldName2="aliasName_"
    fieldName3="baseName_"
    fieldName4="domain_"
    fieldName5="isNullabl_"
    fieldName6="precision_"
    fieldName7="required_"
    fieldName8="scale_"
    fieldName9="type_"
    fieldName10="length_"
    fieldName11="editable_"
    fieldName12="Table_Name"
    fieldLength=255

    # Execute AddField new fields. All fields are set as text even if they contain numbers.
    arcpy.AddField_management(inFeatures, fieldName12, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName1, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName2, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName3, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName4, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName5, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName6, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName7, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName8, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName9, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName10, "TEXT", "", "", fieldLength)
    arcpy.AddField_management(inFeatures, fieldName11, "TEXT", "", "", fieldLength)


by the following:
    fieldLength=255
    field_names = ["field_name", "aliasName_", "baseName_", "domain_", "isNullabl_",
                            "precision_", "required_", "scale_", "type_", "length_", "editable_"]

    for field_name in field_names:
        arcpy.AddField_management(inFeatures, field_name, 'TEXT', '', '', field_length)


Though they won't work everywhere, lists are a great way of consolidating your code and often improving legibility.

Cheers!
Marc
0 Kudos
chriss_
New Contributor II
Hi Marc!
I appreciate your hints.
1) I agree I should handle the error messages more carefully. I've one more question on that. Sometimes when programming python gives me an error message telling me there is a mistake in a certain line(25), but in IDLE Python it is another line(20). Any idea about that?
2) Touché. Just stupidly copied code : )

Thanks again
Chris
0 Kudos
MarcNakleh
New Contributor III
Hi Chris,

No problem at all. Python's website is chock-full of examples you can use as references for good coding (that's how I figured a lot of stuff out!)

When it comes to your issue of disparate errors, I'd need a bit more information: could you give a specific example of the errors? When you say you are "programming python" (vs. "using IDLE"), what programming environment are you programming in (i.e. what is the program sending you errors?) Is it PythonWin or some other editor?

Cheers,
Marc
0 Kudos
chriss_
New Contributor II
Hi Mark!
Thanks again. It gets a little bit off topic so I will start a new topic on how to use python in a better way when I find some time.
Thanks again
Cu around
0 Kudos