lstFields = arcpy.ListFields(fc) x = False for field in lstFields: if field.name == "USNG": print "Field exists" x = True if x <> True: print "Field does not exist"
lstFields = arcpy.ListFields(fc) if "USNG" in lstFields: print "Field exists" else: print "Field does not exist"
>>> a = [3,5,6,'kitty'] # a Python list >>> b = 2 >>> b in a False >>> c = 5 >>> c in a True >>> d = 'kitty' >>> d in a True >>>
if arcpy.ListFields(tbl, field_name): print "Field exists" else: print "Field doesn't exist"
This is the most direct. Your code is so clear and concise. Well done!
Stacy's arcpy.ListFields returns a list of field objects (not field names) so the "in" operator would not work. You could make it work by converting the list to field names (and converting to upper case because the in operator is case sensitive).
lstFields <SPAN class="operator token">=</SPAN> arcpy<SPAN class="punctuation token">.</SPAN>ListFields<SPAN class="punctuation token">(</SPAN>fc<SPAN class="punctuation token">)</SPAN> field_names <SPAN class="operator token">=</SPAN> <SPAN class="punctuation token">[</SPAN>f<SPAN class="punctuation token">.</SPAN>name<SPAN class="punctuation token">.</SPAN>upper<SPAN class="punctuation token">(</SPAN><SPAN class="punctuation token">)</SPAN> <SPAN class="keyword token">for</SPAN> f <SPAN class="keyword token">in</SPAN> lstFields<SPAN class="punctuation token">]</SPAN> <SPAN class="keyword token">if</SPAN> <SPAN class="string token">"USNG"</SPAN> <SPAN class="keyword token">in</SPAN> field_names<SPAN class="punctuation token">:</SPAN> <SPAN class="keyword token">print</SPAN> <SPAN class="string token">"Field exists"</SPAN> <SPAN class="keyword token">else</SPAN><SPAN class="punctuation token">:</SPAN> <SPAN class="keyword token">print</SPAN> <SPAN class="string token">"Field does not exist"</SPAN><SPAN class="line-numbers-rows"><SPAN></SPAN><SPAN></SPAN><SPAN></SPAN><SPAN></SPAN><SPAN></SPAN><SPAN></SPAN></SPAN>
Tested Stacy's code above and curtvprice is correct, the "in" operator will not work.
This code worked for me. Using a couple for loops I was able to run this against multiple feature classes within multiple feature datasets to determine if a field was present.
Přihlášení členové mohou přispívat, sledovat aktualizace a další. Jste tu noví? Zaregistrujte si bezplatný účet.
Find useful guides, FAQs, and documents to help you navigate and make the most of Esri Community.