add a list in arcpy.MakeFeatureLayer_management

1300
13
Jump to solution
09-19-2022 05:53 AM
danielROUFFART1
New Contributor II

Hi! i ty to make

 

 

 

 

output = r'C:\Temp\test.gdb\BAV1'
target = r'C:\download

fcs2 = [a, b, c, d]
# Set the workspace
arcpy.env.workspace = ready
for x in range(len(fcs2)):
    arcpy.MakeFeatureLayer_management(fcs2, output)

arcpy.SelectLayerByAttribute_management(output, 'NEW_SELECTION', "city = 'Paris'")

arcpy.CopyFeatures_management(output, target)

but i've got an error message, can you help me about my script for put my list please

Tags (1)
0 Kudos
1 Solution

Accepted Solutions
by Anonymous User
Not applicable

If your fields change between featureclasses, and the sql needs to change between each featureclass, you can use if/elif to create your sql.

arcpy.env.overwriteOutput = True #<- move to top of script since it only needs to be set once


for fc in fcs2:
    # fichier temporaire d'affinage de la selection
    flds = [f.name for f in arcpy.ListFields(fc)]
    # create empty whereclause variable
    whereclause = None

    if 'commune' in flds:
        whereclause = f"""{arcpy.AddFieldDelimiters(fc, 'commune')} = 'Perpignan'"""

    elif 'nomcom' in flds:
        # build the query using field deliminators
        whereclause = f"""{arcpy.AddFieldDelimiters(fc, 'nomcom')} = 'SALEILLES'"""

    else:
        print(f'commune not found in {fc}')

    if whereclause:
        # describe first to get the name
        fc_desc = arcpy.Describe(fc)
        print("fc_desc")
        print (fc_desc)
        # create the temp layer with selection
        tmpLyr = arcpy.MakeFeatureLayer_management(fc, fc_desc.name + '_lyr', whereclause)
        out_name = fc_desc.baseName + '_export'
        print (out_name)
        new_name = fc_desc.name.replace('.','_').replace('rezo_h','')
        print(new_name)
        ditched_features_path = os.path.join(out_name, sauve + "\_"+ new_name)
        print (ditched_features_path)
        # copie de la selection en shape
        arcpy.CopyFeatures_management(tmpLyr, ditched_features_path)
    else:
        print ("no data")

 

View solution in original post

0 Kudos
13 Replies
danielROUFFART1
New Contributor II

so i try to make a loop with this code but i've got this error message

 

 


 

arcpy.env.workspace = ready
for i in fcs:
    arcpy.MakeFeatureLayer_management(i, output)
    print("couche temp")
    # fichier temporaire d'affinage de la selection
    arcpy.SelectLayerByAttribute_management(output, 'NEW_SELECTION', "commune = 'Perpignan'")
    fc_desc = arcpy.Describe(i)
    out_name = fc_desc.baseName + 'export'
    ditched_features_path = os.path.join(out_name,saved)
    # copie de la selection en shape
    arcpy.CopyFeatures_management(output, ditched_features_path)​

 


arcgisscripting.ExecuteError: ERROR 000358: Invalid expression
0 Kudos
BlakeTerhune
MVP Regular Contributor

Does the traceback of the error mention what line the error occurs on? If so, please identify the matching line in the code snippet you posted.

0 Kudos
danielROUFFART1
New Contributor II

yes it say it's here:

arcpy.SelectLayerByAttribute_management(output, 'NEW_SELECTION', "commune = 'Perpignan'")

i think it's about the sql clause, because when i try my script with one feature everything it's ok, but with a loop it's don't work.

 

 

 


0 Kudos
JoshuaBixby
MVP Esteemed Contributor

Also, what format is your data source?  Shape file, file geodatabase, .... 

0 Kudos
danielROUFFART1
New Contributor II

yes it's a geodatabase

0 Kudos
RhettZufelt
MVP Frequent Contributor

Original line 4 is setting a variable to a list of undefined variables.  Should not be getting past that line without error unless you have defined them elsewhere.

If there are actually feature classes a, b c, and d in the workspace "ready" (if you have defined ready anywhere), then you would want quotes around the list items.

fcs2 = ['a', 'b', 'c', 'd']

R_

 

0 Kudos
danielROUFFART1
New Contributor II

no it's just a part of my script if you wanna see him completly it' here

# Import system modules
import arcpy
import os
import shutil
import glob


# mise en place de balises
arcpy.env.overwriteOutput = True
input = r'C:\Users\user\AppData\Roaming\Esri\ArcGISPro\Favorites\TEST\
test.InvestOPERATIONS_STOCK_test'
output = r'C:\Temp\test.gdb'
Rezo = r'\\Rezo.sde'

targetPattern = r"C:\Users\**\Downloads\zipla"

Saved = glob.glob(targetPattern)
sauve = ''.join(Saved)
print (Saved)
print (sauve)
AEP = "\AEP_Régie"
joiend = [Saved,AEP]
print (joiend)

for target in joiend:
    # JOIN TARGET
    target = (''.join([''.join(Saved),AEP]))

print (target)
#######################################################################################################################
#recherche couches AEP
targetPattern=r"C:\Users\**\AppData\Roaming\Esri\ArcGISPro\Favorites"
target = glob.glob(targetPattern)
print (target)
joiend = [target,Rezo]

for ready in joiend:
    # JOIN TARGET
    ready = (''.join([''.join(target),r'\Rezo_h@geom06.sde\rezo_h.geom04.REGIE_EAU_POTABLE']))

print (ready)
ready2 = ready+"\\"
arcpy.env.workspace = ready

fcs = arcpy.ListFeatureClasses("rezo_h.AEP*")
print ("fcs")
print (fcs)


fcs2 = [ready2+ str(i) for i in fcs]



print ("fcs2")
print (fcs2)


#######################################################################################################################
# Set the workspace
arcpy.env.workspace = ready
for i in fcs2:
    arcpy.MakeFeatureLayer_management(i, output)
    print('lyr')
    # fichier temporaire d'affinage de la selection
    whereclause = "commune = 'Perpignan'"
    arcpy.SelectLayerByAttribute_management(output, 'NEW_SELECTION', whereclause)
    fc_desc = arcpy.Describe(i)
    print("fc_desc")
    print (fc_desc)
    out_name = fc_desc.baseName + '_export'
    print (out_name)

    ditched_features_path = os.path.join(out_name, sauve + "\outfile")
    # copie de la selection en shape
    arcpy.CopyFeatures_management('lyr', ditched_features_path)


#######################################################################################################################


filename = r"C:\Users\d.rouffart\Downloads\zipla"
format = "zip"
directory = os.getcwd()
shutil.make_archive(filename, format, directory)
0 Kudos
RhettZufelt
MVP Frequent Contributor

Not sure if it likes r'C:\Temp\test.gdb' as a layer name in MakeFeatureLayer.  Also, lot of issues trying to re-use the layer name in arcpy, doesn't seem to let you just delete them and reuse in a loop.

You might try something similar to below and append _lyr to the end of the FC as the output to make feature and input to Select.....   This way, it will be a unique layer name for each iteration.

 

    arcpy.MakeFeatureLayer_management(i, i + "_lyr")
    print('lyr')
    # fichier temporaire d'affinage de la selection
    whereclause = "commune = 'Perpignan'"
    arcpy.SelectLayerByAttribute_management(i + "_lyr", 'NEW_SELECTION', whereclause)

 

 

Also, seems like there is an extra step going on here.  If you put the whereclause in the MakeFeatureLayer then just use that output for the copy features you wouldn't need the Select by Attributes.

R_

 

 

0 Kudos
danielROUFFART1
New Contributor II

thanks , I try your solution but i've got the same message :

Traceback (most recent call last):
  File "C:/Users/d.rouffart/Desktop/script Py/gxdh.py", line 69, in <module>
    arcpy.SelectLayerByAttribute_management(i + "_lyr", 'NEW_SELECTION', whereclause)
  File "C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\management.py", line 9574, in SelectLayerByAttribute
    raise e
  File "C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\management.py", line 9571, in SelectLayerByAttribute
    retval = convertArcObjectToPythonObject(gp.SelectLayerByAttribute_management(*gp_fixargs((in_layer_or_view, selection_type, where_clause, invert_where_clause), True)))
  File "C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\geoprocessing\_base.py", line 511, in <lambda>
    return lambda *args: val(*gp_fixargs(args, True))
arcgisscripting.ExecuteError: ERROR 000358: Invalid expression
Échec de l’exécution de (SelectLayerByAttribute).

but when i think my expression is good

 

 

 

0 Kudos