Search code examples
pythonarcgisarcpyarcmap

Finding Null value form shape file attribute fields using python


I have 100 shape files from different sub folders. I want to check "Population" field in each shape file. If the "Population" field in any of the shape file is ["", " ", None] then print me the name of those particular shape files.

import os  
import fnmatch  
import arcpy  
rootPath = r"C:\Project\layers"   
pattern = 'mig*.shp'   
for root, dirs, files in os.walk(rootPath):   
    for filename in fnmatch.filter(files, pattern):   
        shp = os.path.join(root, filename)  
        if arcpy.ListFields(shp, "Population"):  
            print("{} has Population field".format(shp))   
            with arcpy.da.SearchCursor(shp, ["Population"]) as rows:  
                for row in rows:  
                    if row[0] == ["", " ", None]:  
                        print("{} has a empty value".format(shp))
                    else:
                            print "OK"

the script working fine to find shape files name those are having population field. But its not working to find shape name which are having empty population field.

I am getting "runtime error". TypeError: String indices must be integers, not str.


Solution

  • I'd rather add it as a comment to your question, but I cannot. First of all, if you want to check if field is empty please change the line:

    if row[0] == ["", " ", None]:
    

    to:

    if row[0] in ["", " ", None]:
    

    But this is logical error that shouldn't result in runtime error. Please make also sure that indent of print "OK" in last line is correct.

    Run the code below and let us know if runtime error is still there. If yes, please provide more information (including line of the error):

    import os  
    import fnmatch  
    import arcpy  
    rootPath = r"C:\Project\layers"   
    pattern = 'mig*.shp'   
    for root, dirs, files in os.walk(rootPath):   
        for filename in fnmatch.filter(files, pattern):   
            shp = os.path.join(root, filename)  
            if arcpy.ListFields(shp, "Population"):  
                print("{} has Population field".format(shp))   
                with arcpy.da.SearchCursor(shp, ["Population"]) as rows:  
                    for row in rows:  
                        if row[0] in ["", " ", None]:  
                            print("{} has a empty value".format(shp))
                        else:
                            print "OK"