Tuesday, 24 January 2017

arcgis 10.4 - Using fieldinfo.setVisible in ArcPy?



I went through the documentation, and searched around but wasn't able to figure this out. What I want to do is export shapefiles, but have certain fields turn off. I was successful in turning off regular fields with delete.field.management, but I was unable to delete the FID field, so now I am looking into turning the field off, instead of deleting it. Below is a part of the sample code I am working on before I fill in with my data -


fields= arcpy.ListFields(out_layer_file)

# Create a fieldinfo object
fieldinfo = arcpy.FieldInfo()

# Iterate through the fields and set them to fieldinfo
for field in fields:
if field.name == "FID":
fieldinfo.setVisible(field.name, "HIDDEN")



arcpy.MakeFeatureLayer_management(out_layer_file, "New2", field_info)
arcpy.SaveToLayerFile_management("New2", out_layer_file1, "ABSOLUTE")

Most of this was taken from ESRI, there isn't a lot of info on fieldinfo. I am new to python in general and trying to figure this out my error is this:



type 'exceptions.AttributeError': FieldInfo: Error in parsing arguments for SetVisible



Its not the FID field because even if I change it to a regular field I still get the error.



Any ideas - or any other documents on how to go about this?



Answer



You should be getting the Field Info of an existing layer, not creating an empty Field Info object. Instead of using arcpy.FieldInfo(), you need to use arcpy.Describe() on your layer first, and then you can use the Layer property FieldInfo.


desc = arcpy.Describe(out_layer_file)
field_info = desc.fieldInfo

# List of fields to hide
# desc.OIDFieldName is the name of the 'FID' field
fieldsToHide = [desc.OIDFieldName, 'OtherFieldOne', 'OtherFieldTwo']


for i in range(0, field_info.count):
if field_info.getFieldName(i) in fieldsToHide:
field_info.setVisible(i, "HIDDEN")

arcpy.MakeFeatureLayer_management(out_layer_file, "New2", "", "", field_info)

Also, in your MakeFeatureLayer() line you were setting your field_info however there were two more properties between the feature layer name and the field_info property, so Make Feature Layer thought you were passing your field_info as a where_clause. See Make Feature Layer help.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...