How do you remove tables/table views from the table of contents (TOC) in the map document?

I've written code that cleans things up after each tool run, but I cannot figure out how to get rid of the tables. The most I've been able to do is delete them from the geodatabase, but then they just remain in the TOC with broken connections:

# ---------------------------------------------------------------
# Clean up the gdb & map docoument from previous script executions
# ---------------------------------------------------------------
goodFCs = ["NYC_Subway_Stations", "NYC_2010_CensusBlocks_BasicDemographics", "NYC_Borough_Boundaries"]

mxd = arcpy.mapping.MapDocument("CURRENT")
for df in arcpy.mapping.ListDataFrames(mxd):
    for lyr in arcpy.mapping.ListLayers(mxd, "", df):
        if lyr.name not in goodFCs:
            arcpy.mapping.RemoveLayer(df, lyr)
    for tbl in arcpy.mapping.ListTableViews(mxd):

allFcs = arcpy.ListFeatureClasses()
for fc in allFcs:
    if fc not in goodFCs:   

Image 1: Once it's run a second (or third or fifth, etc.) time, my script will successfully remove the map layers highlighted in yellow, but not the tables inside the red box:

enter image description here

Image 2: After the second script run, yellow map layers will have been successfully replaced with new yellow map layers, but the old tables will remain with broken links. I want to get rid of them completely:

enter image description here

I'm aware that I don't have any code written to remove the tables, but that's because I don't know what code to write. Tables aren't inside of the dataframe so I can't use arcpy.mapping.RemoveLayer(), which takes a dataframe as its first required parameter...


You should be able to use RemoveTableView just like you use RemoveLayer in your code:

for tbl in arcpy.mapping.ListTableViews(mxd, "", df):
    arcpy.mapping.RemoveTableView(df, tbl)


| improve this answer | |

There's a mapping.RemoveTableView function to do this.

for tab in arcpy.mapping.ListTableViews (mxd):
     arcpy.mapping.RemoveTableView (df, tab)
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.