# Import arcpy moduleimport arcpy# Define the input feature class or tablefc = arcpy.GetParameterAsText(0)# Get a list of all fields in the input feature class or tablefields = arcpy.ListFields(fc)# Loop through each field and delete it (except for OBJECTID and SHAPE)for field in fields: if field.name != "OBJECTID" and field.name != "SHAPE": arcpy.DeleteField_management(fc, field.name)# Print a message to indicate that the fields have been deletedarcpy.AddMessage("All non-required fields have been deleted from " + fc)运行错误:Traceback (most recent call last): File "D:\多对一空间连接\删除所有字段.py", line 13, in <module> File "c:\program files (x86)\arcgis\desktop10.2\arcpy\arcpy\management.py", line 3479, in DeleteField raise e ExecuteError: 执行失败。参数无效。 ERROR 001334: 无法删除必需字段 SHAPE_Length 执行(DeleteField)失败。 执行(删除所有字段)失败。请改正代码
时间: 2023-12-11 18:02:57 浏览: 133
这个错误是因为你的代码尝试删除了 SHAPE_Length 这个必需字段,导致删除操作失败。你需要在代码中加入一个判断,跳过必需字段的删除。修改后的代码如下:
```python
# Import arcpy module
import arcpy
# Define the input feature class or table
fc = arcpy.GetParameterAsText(0)
# Get a list of all fields in the input feature class or table
fields = arcpy.ListFields(fc)
# Loop through each field and delete it (except for OBJECTID and SHAPE)
for field in fields:
if field.name != "OBJECTID" and not field.required:
arcpy.DeleteField_management(fc, field.name)
# Print a message to indicate that the fields have been deleted
arcpy.AddMessage("All non-required fields have been deleted from " + fc)
```
这样修改后,你的代码就可以正确地删除所有非必需字段了。
相关问题
# Import arcpy moduleimport arcpy# Define the input feature class or tablefc = arcpy.GetParameterAsText(0)# Get a list of all fields in the input feature class or tablefields = arcpy.ListFields(fc)# Loop through each field and delete itfor field in fields: arcpy.DeleteField_management(fc, field.name)# Print a message to indicate that the fields have been deletedarcpy.AddMessage("All fields have been deleted from " + fc)运行出错:Traceback (most recent call last): File "D:\多对一空间连接\删除所有字段.py", line 12, in <module> File "c:\program files (x86)\arcgis\desktop10.2\arcpy\arcpy\management.py", line 3479, in DeleteField raise e ExecuteError: 执行失败。参数无效。 ERROR 001334: 无法删除必需字段 OBJECTID 执行(DeleteField)失败。请改正代码
这个错误是因为你试图删除必需字段 "OBJECTID",这是每个要素类的默认字段,无法删除。如果你想删除除了 "OBJECTID" 以外的所有字段,可以在删除之前添加一个条件来排除这个字段。修改你的代码如下:
```python
# Import arcpy module
import arcpy
# Define the input feature class or table
fc = arcpy.GetParameterAsText(0)
# Get a list of all fields in the input feature class or table
fields = arcpy.ListFields(fc)
# Loop through each field and delete it (except for OBJECTID)
for field in fields:
if field.name != "OBJECTID":
arcpy.DeleteField_management(fc, field.name)
# Print a message to indicate that the fields have been deleted
arcpy.AddMessage("All fields (except for OBJECTID) have been deleted from " + fc)
```
这个修改后的代码应该可以正常运行,并且不会删除必需字段 "OBJECTID"。
阅读全文