Select Layer by Location not providing correct result.

2331
28
Jump to solution
02-12-2013 09:45 AM
SusanWhitney
New Contributor III
I sought assistance with a portion of this code earlier. I have added an additional step, which to me would seem pretty simple, but I am still learning the ups & downs of Python.

My script creates data driven pages. I use a list to populate a layer definition query to run a specific township. Now I am trying to do a selection (SelectLayerByLocation) to only find the townships where there is data. I first just added the SelectLayerByLocation command. Did not work. With further reading, it looked like I needed to run a MakeFeatureLayer on the two sets of data involved in the selection. Still did not work. Do I need to use cursors or is the answer much simpler?

I do not have any error messages. I have added try/except to see if I can find additional information on what is happening with my script. The data exports just fine, but there are maps that do not have any data.
Thank you for any guidance.

# PoleDDpages.py # Author: slw # Date: XXXXX # Revisions: XXXXX # Description: Create Pole map book series using Data Driven Pages and #           insert a cover page  # Import ArcPy import os,arcpy  try:          # Set up variables     # Location of pole map .mxd document     mxdDoc = r"G:\GEOSPATIAL\Publishing\Pole\Pole_QtrSec.mxd"      # Create the MapDocument object     mxd = arcpy.mapping.MapDocument(mxdDoc)     df = arcpy.mapping.ListDataFrames(mxd)[0]     layer = arcpy.mapping.ListLayers (mxd, "SURVEY_GRID_BNDRY",df)[0]     poleLyr = arcpy.mapping.ListLayers (mxd, "Pole",df)[0]      # Overwrite existing file     arcpy.env.overwriteOutput = True      # Output directory for the pole maps     outDir = r"G:\GEOSPATIAL\Publishing\Pole"      # Set the workspace     arcpy.env.workspace = outDir      # List of map grids     twpList = ['\"TOWNSHIP_C\" = \'D5\' AND \"RANGE_CD\" = \'5\'',\                '\"TOWNSHIP_C\" = \'D6\' AND \"RANGE_CD\" = \'4\'']       i=1     for twpName in twpList:         layer.definitionQuery = twpName          # refresh() after changing the layer def query to 'redefine' the DDP index limits         mxd.dataDrivenPages.refresh()                 # Create temporary layers to work with the Selection         arcpy.MakeFeatureLayer_management(layer, "surveyLyr")         arcpy.MakeFeatureLayer_management(poleLyr, "poleLyr_new")          # Clear the Selection before starting         #arcpy.SelectLayerByAttribute_management("surveyLyr", "CLEAR_SELECTION", "")         #print "The selection has been cleared"                  # Select Layer By Location to limit to just maps with data         arcpy.SelectLayerByLocation_management("surveyLyr", "INTERSECT", "poleLyr_new", "", "NEW_SELECTION")          # refresh() after changing the layer def query to 'redefine' the DDP index limits         mxd.dataDrivenPages.refresh()          mxd.saveACopy(os.path.splitext(mxdDoc) [0] + str(i) + os.path.splitext(mxdDoc)[1])         i += 1                   # The final mapbook name taken from the list         finalPDFfn = outDir + "\\" + twpName [16:18] + twpName [38:39] + "Pole.pdf"                  # Create the final PDF -- which is just an empty shell right now         finalPDF = arcpy.mapping.PDFDocumentCreate(finalPDFfn)          # A temporary pdf file for processing         tmpPDF = outDir + "\\PoleMapPages.pdf"          # Let the user know what is happening!         print "Exporting " + twpName [16:18] + twpName [38:39]                  # Export the data driven pages in the mxd to a temporary PDF         print "Exporting map pages to the temporary PDF"         ddp = mxd.dataDrivenPages.exportToPDF(tmpPDF)          # Append the temporary pdf to the final pdf         # Cover, map pages, back cover         print "Appending Map Pages"         finalPDF.appendPages (r"G:\GEOSPATIAL\Publishing\Pole\PoleCovers\Covers_"\                               + twpName [16:18] + twpName [38:39] + ".pdf")         finalPDF.appendPages(tmpPDF)         finalPDF.appendPages(r"G:\GEOSPATIAL\Publishing\TwpGrid_Color8x11.pdf")          # Set properties for Adobe Reader and save PDF.         finalPDF.updateDocProperties(pdf_open_view = "USE_THUMBS", pdf_layout = "SINGLE_PAGE")         finalPDF.saveAndClose()          # Deleting temporary layers         arcpy.Delete_management("surveyLyr")         arcpy.Delete_management("poleLyr_new")      except Exception as e:     print e.message     print arcpy.GetMessages(2)      # Clean up print "Cleaning up" # Delete the temporary PDF using the ArcPy function if arcpy.Exists(tmpPDF):                  arcpy.Delete_management(tmpPDF)   # Delete objects del mxd, tmpPDF, ddp               # Finished message print "Map compilation completed. Please review the final output."
Tags (2)
0 Kudos
28 Replies
T__WayneWhitley
Frequent Contributor
So the new block to select the appropriate index grid subset is working?...except for when the query produces an empty set?

Right so what you could do is modify to test the query in your loop - you have to test the formed query before setting the def:

layer.definitionQuery = twpName + " AND \"OBJECTID\" NOT IN " + str(subquery)

...so what you could do is execute a MFL on the index and test with getCount to see if it is zero (0) and if so, of course loop immediately to your 2nd query, right?

So, something like (within the loop, so you can get twpName) - I did not test this, so check my command puctuation, etc:
query = twpName + " AND \"OBJECTID\" NOT IN " + str(subquery)
arcpy.MakeFeatureLayer_management('the index', 'theTestLyrForCount', query)
TheCountBeforeExecutingRestOfLoop = int(arcpy.GetCount_management('theTestLyrForCount').getOutput(0))

if TheCountBeforeExecutingRestOfLoop != 0:
     layer.definitionQuery = query
     # finish executing the loop, etc. - don't forget to indent this region of code.
     # the following lines must be justified, i.e., indented with 'layer.definitionQuery...


Understand?  ...you are almost there, if you don't understand or if this code is 'ugly', it can be fixed later.  Output today without error is essential, lol!


Enjoy,
Wayne
0 Kudos
T__WayneWhitley
Frequent Contributor
Susan, test this please - added 'if' block to test for empty set as a result of query...think I got the indention right, but check:
# PoleDDpages.py
# Author: slw
# Date: XXXXX
# Revisions: XXXXX
# Description: Create Pole map book series using Data Driven Pages and
#           insert a cover page

# Import ArcPy
import os,arcpy

# Overwrite existing file
arcpy.env.overwriteOutput = True

try:
    
    # Set up variables
    # Location of pole map .mxd document
    mxdDoc = r"G:\GEOSPATIAL\Publishing\Pole\Pole_QtrSec.mxd"

    # Create the MapDocument object
    mxd = arcpy.mapping.MapDocument(mxdDoc)
    df = arcpy.mapping.ListDataFrames(mxd)[0]
    layer = arcpy.mapping.ListLayers (mxd, "SURVEY_GRID_BNDRY",df)[0]
    poleLyr = arcpy.mapping.ListLayers (mxd, "Pole",df)[0]

    ################
    # moved part of code to select grids (layer) intersecting 'Pole' features (poleLyr)
    # Create temporary layers to work with the Selection,
    # 1st need to assure no prior selections...the sel by loc syntax:
    # SelectLayerByLocation_management (in_layer, {overlap_type}, {select_features}, {search_distance}, {selection_type})
    # in_layer is the index layer; select_features is the pole layer
    
    SelectBy = [layer, poleLyr]
    for lyr in SelectBy:
          iniCount = int(arcpy.GetCount_management(lyr).getOutput(0))
          if iniCount != 0:
               arcpy.SelectLayerByAttribute_management(lyr, 'CLEAR_SELECTION')

    # should now be properly 'initialized' with no prior selections, i.e., full complement datasets      
    arcpy.MakeFeatureLayer_management(layer, "surveyLyr")
    arcpy.MakeFeatureLayer_management(poleLyr, "poleLyr_new")
        
    # Select Layer By Location to limit to just maps with data
    arcpy.SelectLayerByLocation_management("surveyLyr", "INTERSECT", "poleLyr_new", "", "NEW_SELECTION")

    # Susan, check that this works, switching the selection...
    # SelectLayerByAttribute_management (in_layer_or_view, {selection_type}, {where_clause})
    arcpy.SelectLayerByAttribute_management("surveyLyr", "SWITCH_SELECTION")

    # new code to get at OBJECTIDs to modify def query
    IDs = []
    rows = arcpy.SearchCursor("surveyLyr")
    for row in rows:
          IDs.append(row.OBJECTID)

    del row, rows

    subquery = '('
    for each in IDs:
         subquery = subquery + str(each) + ','

    subquery = subquery[0:-1] + ')'
    ################

    # Output directory for the pole maps
    outDir = r"G:\GEOSPATIAL\Publishing\Pole"

    # Set the workspace
    arcpy.env.workspace = outDir

    # List of map grids
    twpList = ['\"TOWNSHIP_C\" = \'D5\' AND \"RANGE_CD\" = \'5\'',\
               '\"TOWNSHIP_C\" = \'D6\' AND \"RANGE_CD\" = \'4\'']

    for twpName in twpList:
        # need to test the twpName with the added subquery for empty return 1st
        theQuery = twpName + " AND \"OBJECTID\" NOT IN " + str(subquery)

        # create a feature layer on index with which to test theQuery for empty set
        # MakeFeatureLayer_management (in_features, out_layer, {where_clause})
        arcpy.MakeFeatureLayer_management(layer, "testTheCount", theQuery)
        gridsToOutput = int(arcpy.GetCount_management("testTheCount").getOutput(0))

        if gridsToOutput != 0:

            # modified the definitionQuery to include the subquery exclusion clause
            layer.definitionQuery = theQuery

            # refresh() after changing the layer def query to 'redefine' the DDP index limits
            mxd.dataDrivenPages.refresh()
             
            # The final mapbook name taken from the list
            finalPDFfn = outDir + "\\" + twpName [16:18] + twpName [38:39] + "Pole.pdf"
            
            # Create the final PDF -- which is just an empty shell right now
            finalPDF = arcpy.mapping.PDFDocumentCreate(finalPDFfn)

            # A temporary pdf file for processing
            tmpPDF = outDir + "\\PoleMapPages.pdf"

            # Let the user know what is happening!
            print "Exporting " + twpName [16:18] + twpName [38:39]
            
            # Export the data driven pages in the mxd to a temporary PDF
            print "Exporting map pages to the temporary PDF"
            ddp = mxd.dataDrivenPages.exportToPDF(tmpPDF)

            # Append the temporary pdf to the final pdf
            # Cover, map pages, back cover
            print "Appending Map Pages"
            finalPDF.appendPages (r"G:\GEOSPATIAL\Publishing\Pole\PoleCovers\Covers_"\
                                  + twpName [16:18] + twpName [38:39] + ".pdf")
            finalPDF.appendPages(tmpPDF)
            finalPDF.appendPages(r"G:\GEOSPATIAL\Publishing\TwpGrid_Color8x11.pdf")

            # Set properties for Adobe Reader and save PDF.
            finalPDF.updateDocProperties(pdf_open_view = "USE_THUMBS", pdf_layout = "SINGLE_PAGE")
            finalPDF.saveAndClose()

    # Deleting temporary layers
    arcpy.Delete_management("surveyLyr")
    arcpy.Delete_management("poleLyr_new")
    arcpy.Delete_management("testTheCount")

except Exception as e:
    print e.message
    print arcpy.GetMessages(2)
    
# Clean up
print "Cleaning up"
# Delete the temporary PDF using the ArcPy function
if arcpy.Exists(tmpPDF):         
        arcpy.Delete_management(tmpPDF)  
# Delete objects
del mxd, tmpPDF, ddp             

# Finished message
print "Map compilation completed. Please review the final output."


A thing worth noting here is if you're working within IDLE or some other editor, etc., is that when you enter a block where succeeding code will require indenting, you may select the code and indent the whole 'region' (in IDLE, it's Format >> Indent Region, on the main menu)...just have to be careful about mixing indention, spaces and tabs.

Hope that helps - do you think I warrant this as 'answered' well enough to get the green checkmark?  Just wondering - I've learned a lot and hope you have too.


Thanks and enjoy,
Wayne
0 Kudos
SusanWhitney
New Contributor III
I now have 3 townships in my list. The first and last have data, the middle or second one will result in no map sheets or no poles. The script will create the first .pdf but will not create the third .pdf ... Do we need an elif statement?
0 Kudos
T__WayneWhitley
Frequent Contributor
Repost your code, as it is now, or if you only changed the query, post that part - guess you mean the list, twpList, now has a 3rd member?

Also, check all your 'virtual' or in-mem feature layer references - could be that's getting out of control, maybe indention isn't right or something is not being cleared.  No errors, right?

One more thing, print and manually check what the separate queries produce, as before when I had you troubleshoot manually refreshing the DDP.

...I haven't looked at you export process yet - are there any references there that aren't behaving?


Enjoy,
Wayne
0 Kudos
SusanWhitney
New Contributor III
Just as a follow up. I am working on this between other items.  I have added print statements and I have replaced the township that does not have any resulting data with one that does. I get the same result with the last code that you provided. The script will look at D55, print that it has 2 pages, and create the .pdf. It then shows the next township (now using B84) has zero pages. I am working on deciphering some of the code (remember I am a newbie) so maybe I can find out why subsequent townships count as zero pages.

Thank you,
Susan
0 Kudos
SusanWhitney
New Contributor III
Good morning,
I am sorry to be such a needy scripter. If you don't have the time to look at this, I understand.
I used the last code that you wrote and put 3 townships in my list. All 3 townships should result in pages with data in the .pdf. The script only outputs the first map, and then shows that the next two maps have zero pages. I have attached a map package. This contains the pole data to be displayed, the index layer, and the pole layer to be used for intersection. It also contains a back cover and 4 cover pages. I included the data for the 3 townships with data and one without (D64).
Thank you

# PoleDDpages.py
# Author: slw
# Date: XXXXX
# Revisions: XXXXX
# Description: Create Pole map book series using Data Driven Pages and
#           insert a cover page

# Import ArcPy
import os,arcpy

# Overwrite existing file
arcpy.env.overwriteOutput = True

try:
    
    # Set up variables
    # Location of pole map .mxd document
    mxdDoc = r"G:\GEOSPATIAL\Publishing\Pole\Pole_QtrSec.mxd"

    # Create the MapDocument object
    mxd = arcpy.mapping.MapDocument(mxdDoc)
    df = arcpy.mapping.ListDataFrames(mxd)[0]
    layer = arcpy.mapping.ListLayers (mxd, "SURVEY_GRID_BNDRY",df)[0]
    poleLyr = arcpy.mapping.ListLayers (mxd, "Pole",df)[0]

    ################
    # moved part of code to select grids (layer) intersecting 'Pole' features (poleLyr)
    # Create temporary layers to work with the Selection,
    # 1st need to assure no prior selections...the sel by loc syntax:
    # SelectLayerByLocation_management (in_layer, {overlap_type}, {select_features}, {search_distance}, {selection_type})
    # in_layer is the index layer; select_features is the pole layer
    
    SelectBy = [layer, poleLyr]
    for lyr in SelectBy:
          iniCount = int(arcpy.GetCount_management(lyr).getOutput(0))
          if iniCount != 0:
               arcpy.SelectLayerByAttribute_management(lyr, 'CLEAR_SELECTION')

    # should now be properly 'initialized' with no prior selections, i.e., full complement datasets      
    arcpy.MakeFeatureLayer_management(layer, "surveyLyr")
    arcpy.MakeFeatureLayer_management(poleLyr, "poleLyr_new")
        
    # Select Layer By Location to limit to just maps with data
    arcpy.SelectLayerByLocation_management("surveyLyr", "INTERSECT", "poleLyr_new", "", "NEW_SELECTION")

    # Susan, check that this works, switching the selection...
    # SelectLayerByAttribute_management (in_layer_or_view, {selection_type}, {where_clause})
    arcpy.SelectLayerByAttribute_management("surveyLyr", "SWITCH_SELECTION")

    # new code to get at OBJECTIDs to modify def query
    IDs = []
    rows = arcpy.SearchCursor("surveyLyr")
    for row in rows:
          IDs.append(row.OBJECTID)

    del row, rows

    subquery = '('
    for each in IDs:
         subquery = subquery + str(each) + ','

    subquery = subquery[0:-1] + ')'
    ################

    # Output directory for the pole maps
    outDir = r"G:\GEOSPATIAL\Publishing\Pole"

    # Set the workspace
    arcpy.env.workspace = outDir

    # List of map grids
    twpList = ['\"TOWNSHIP_C\" = \'D5\' AND \"RANGE_CD\" = \'5\'',\
               '\"TOWNSHIP_C\" = \'C4\' AND \"RANGE_CD\" = \'7\'',\
               '\"TOWNSHIP_C\" = \'B8\' AND \"RANGE_CD\" = \'4\'']

    for twpName in twpList:
        # need to test the twpName with the added subquery for empty return 1st
        theQuery = twpName + " AND \"OBJECTID\" NOT IN " + str(subquery)

        # create a feature layer on index with which to test theQuery for empty set
        # MakeFeatureLayer_management (in_features, out_layer, {where_clause})
        arcpy.MakeFeatureLayer_management(layer, "testTheCount", theQuery)
        gridsToOutput = int(arcpy.GetCount_management("testTheCount").getOutput(0))
        print "Output " + str(gridsToOutput) + " pages"

        if gridsToOutput != 0:

            # modified the definitionQuery to include the subquery exclusion clause
            layer.definitionQuery = theQuery

            # refresh() after changing the layer def query to 'redefine' the DDP index limits
            print "Refresh DDP"
            mxd.dataDrivenPages.refresh()
             
            # The final mapbook name taken from the list
            finalPDFfn = outDir + "\\" + twpName [16:18] + twpName [38:39] + "Pole.pdf"
            
            # Create the final PDF -- which is just an empty shell right now
            finalPDF = arcpy.mapping.PDFDocumentCreate(finalPDFfn)

            # A temporary pdf file for processing
            tmpPDF = outDir + "\\PoleMapPages.pdf"

            # Let the user know what is happening!
            print "Exporting " + twpName [16:18] + twpName [38:39]
            
            # Export the data driven pages in the mxd to a temporary PDF
            print "Exporting map pages to the temporary PDF"
            ddp = mxd.dataDrivenPages.exportToPDF(tmpPDF)

            # Append the temporary pdf to the final pdf
            # Cover, map pages, back cover
            print "Appending Map Pages"
            finalPDF.appendPages (r"G:\GEOSPATIAL\Publishing\Pole\PoleCovers\Covers_"\
                                  + twpName [16:18] + twpName [38:39] + ".pdf")
            finalPDF.appendPages(tmpPDF)
            finalPDF.appendPages(r"G:\GEOSPATIAL\Publishing\TwpGrid_BW8x11.pdf")

            # Set properties for Adobe Reader and save PDF.
            finalPDF.updateDocProperties(pdf_open_view = "USE_THUMBS", pdf_layout = "SINGLE_PAGE")
            finalPDF.saveAndClose()

    # Deleting temporary layers
    arcpy.Delete_management("surveyLyr")
    arcpy.Delete_management("poleLyr_new")
    arcpy.Delete_management("testTheCount")

except Exception as e:
    print e.message
    print arcpy.GetMessages(2)
    
# Clean up
print "Cleaning up"
# Delete the temporary PDF using the ArcPy function
if arcpy.Exists(tmpPDF):         
        arcpy.Delete_management(tmpPDF)  
# Delete objects
del mxd, tmpPDF, ddp             

# Finished message
print "Map compilation completed. Please review the final output."
0 Kudos
T__WayneWhitley
Frequent Contributor
Susan, I sent you a private message, if you'll check that.  Also, I have a hunch if you want to test it.  That's the only reason I am replying here again at this time.  If the hunch doesn't prove or fix anything, then I'll try to dissect the code and look at your test data later, probably report back to you in another private message as this thread is getting pretty long.

If you're 100 percent sure you should have output from the selection query formed in your loop to pass to the final export code section and you are also confident that final section works fine, then my hunch is the Make Feature Layer operation to test the count needs to be cleared...so I suggest moving the 1 line where you are deleting layers outside the loop for 'test the count':

arcpy.Delete_management("testTheCount")

Move it up just after you set the integer variable, gridsToOuput.  You can place it just before or just after your print statement that you said was reporting zero (0) on successive iterations.  What you can also do is test the 'initial' count on 'layer' - this is before applying the query (remember layer is your map "SURVEY_GRID_BNDRY" which you turned into a 'virtual' or in-memory layer, "surveyLyr").  This count should be the same on successive loops, you set up the loop to further refine by TWN/RNG - by now you should know how to make a GetCount statement.  You can very quickly lose track of all your virtual layers...why testing to see exactly what you have a handle on is what you think it is.

Hope that tells you something...that's what all this testing is about - you'll eventually unravel the mystery!  (and it may not be much to trip up the whole works)

-Wayne
0 Kudos
T__WayneWhitley
Frequent Contributor
I know it is late - I feel somewhat remiss for not updating this sooner, but you know how it is when the reality of job demands interferes...
Important thing now is to post a working correction -- I believe the actual portion causing the error you were experiencing, Susan, was not the definition query and consequent DDP refreshing, but the part afterwards building the PDFs.  The code is below - I still think it could be written a bit 'tighter' and if I have time to fool with it more later, I want to experiment with UpdateLayer for the index layer...but that's an aside.  The code below should be functional, and is quite speedy - more time is taken (as I suspected) actually exporting and appending the pdfs.

Anyway, here it is, actually without any real error trapping...I ran it within IDLE to verify it is working code, checked the pdfs, etc. - correct the pathnames accordingly, strip out what you don't need, and so forth...

Enjoy,
Wayne

import os,arcpy  # Overwrite existing file arcpy.env.overwriteOutput = True  try:          # Set up variables     # Location of pole map .mxd document     mxdDoc = r'E:\qryDefTest\Pole_QtrSec\v10\Pole_QtrSec.mxd'      # Create the MapDocument object     mxd = arcpy.mapping.MapDocument(mxdDoc)     df = arcpy.mapping.ListDataFrames(mxd)[0]          layer = arcpy.mapping.ListLayers (mxd, "SURVEY_GRID_BNDRY",df)[0]     poleLyr = arcpy.mapping.ListLayers (mxd, "Pole",df)[0]      ##############     # Test the count of survey grids before processing     countSurveyGrid = int(arcpy.GetCount_management(layer).getOutput(0))     print "Count of All Survey Grids (Survey_Grid_Bndry) =  " + str(countSurveyGrid) + " pages"           SelectBy = [layer, poleLyr]     for lyr in SelectBy:           iniCount = int(arcpy.GetCount_management(lyr).getOutput(0))           print lyr.name + ' initial count: ' + str(iniCount)           if iniCount != 0:                arcpy.SelectLayerByAttribute_management(lyr, 'CLEAR_SELECTION')                outCount = int(arcpy.GetCount_management(lyr).getOutput(0))                print lyr.name + ' out count: ' + str(outCount)      # should now be properly 'initialized' with no prior selections, i.e., full complement datasets           arcpy.MakeFeatureLayer_management(layer, "surveyLyr")     arcpy.MakeFeatureLayer_management(poleLyr, "poleLyr_new")      countSurveyLyr = int(arcpy.GetCount_management("surveyLyr").getOutput(0))     print "Count of temp layer surveyLyr =  " + str(countSurveyLyr) + " pages"          # Select Layer By Location to limit to just maps with data     arcpy.SelectLayerByLocation_management("surveyLyr", "INTERSECT", "poleLyr_new", "", "NEW_SELECTION")      # Susan, check that this works, switching the selection...     # SelectLayerByAttribute_management (in_layer_or_view, {selection_type}, {where_clause})     arcpy.SelectLayerByAttribute_management("surveyLyr", "SWITCH_SELECTION")      # new code to get at OBJECTIDs to modify def query     IDs = []     rows = arcpy.SearchCursor("surveyLyr")     for row in rows:           IDs.append(row.OBJECTID)      del row, rows     print "delete row, rows"      subquery = '('     for each in IDs:          subquery = subquery + str(each) + ','      subquery = subquery[0:-1] + ')'     ################      # Output directory for the pole maps     outDir = r"E:\qryDefTest\Pole_QtrSec\commondata\userdata"      # Set the workspace     arcpy.env.workspace = outDir      # List of map grids     twpList = ['\"TOWNSHIP_C\" = \'D5\' AND \"RANGE_CD\" = \'5\'',\                '\"TOWNSHIP_C\" = \'C4\' AND \"RANGE_CD\" = \'7\'',\                '\"TOWNSHIP_C\" = \'B8\' AND \"RANGE_CD\" = \'4\'']      i = 1      for twpName in twpList:         # modified the definitionQuery to include the subquery exclusion clause         layer.definitionQuery = twpName + " AND \"OBJECTID\" NOT IN " + str(subquery)         countDefQryLyr = int(arcpy.GetCount_management(layer).getOutput(0))         print '-'         print "Count of temp layer surveyLyr =  " + str(countDefQryLyr) + " pages"          # refresh() after changing the layer def query to 'redefine' the DDP index limits         mxd.dataDrivenPages.refresh()          mxd.saveACopy(os.path.join(outDir, 'test' + str(i) + '.mxd'))         i += 1          testTxt = twpName [16:18] + twpName [38:39] + "Pole.pdf"         #finalPDFfn = outDir + "\\" + twpName [16:18] + twpName [38:39] + "Pole.pdf"         finalPDFfn = os.path.join(outDir, testTxt)         print finalPDFfn          # just before you create it, make sure you delete the last var ref         if os.path.exists(finalPDFfn):             os.remove(finalPDFfn)         finalPDF = arcpy.mapping.PDFDocumentCreate(finalPDFfn)          tmpPDF = outDir + "\\PoleMapPages.pdf"         print 'exporting ' + testTxt         print '...to ' + tmpPDF          if os.path.exists(tmpPDF):             os.remove(tmpPDF)         mxd.dataDrivenPages.exportToPDF(tmpPDF, 'ALL')          print "Appending Map Pages"         Cover = os.path.join(outDir, "Covers_" + testTxt[0:-8] + ".pdf")         print "Appending this page 1st: " + Cover         finalPDF.appendPages(Cover)         print '\n...now appending the rest:'         print tmpPDF         finalPDF.appendPages(tmpPDF)          # final closing treatment         finalPDF.updateDocProperties(pdf_open_view = "USE_THUMBS", pdf_layout = "SINGLE_PAGE")         finalPDF.saveAndClose()         print "\nSave and Close"  except:     print 'error'
0 Kudos
SusanWhitney
New Contributor III
Wayne,
You are the best. The script is working beautifully. Thank you for your time and assistance.
0 Kudos