我试图将一个文件夹中包含的多个shapefile的属性导出到文本文件中。我编写了下面的代码,但它只是将文件名导出到文本文件中。关于我可能做错的任何想法?我已经进行了一段时间的故障排除和研究。
import arcpy
from arcpy import env
arcpy.env.workspace = "C:\\user\\rainfiles"
table = "C:\\user\\rain_files"
outWorkspace = "C:\\user"
fclist = arcpy.ListFields(table)
field_names = [field.name for field in fclist]
for field in fclist:
with open(r'C:\\user\\Exports.txt', 'w') as f:
for field in fclist:
f.write(field + '\n')
with open(r'C:\\user\\Exports.txt', 'r') as f:
w = csv.writer(f)
w.writerow(field_names)
for row in arcpy.SearchCursor(table):
field_vals = [row.getValue(field.name) for field in fclist]
w.writerow(field_vals)
del row
答案 0 :(得分:2)
这是一种方式:
import arcpy
import csv
f = open(r'C:\\user\\Exports.txt', 'w')
w = csv.writer(f, lineterminator='\n')
arcpy.env.workspace = "C:\\user\\rainfiles"
shapefileList = arcpy.ListFeatureClasses("*.shp")
for table in shapefileList:
f.write("Shapefile:\n")
f.write(table + "\n")
fieldList = arcpy.ListFields(table)
field_names = [field.name for field in fieldList]
w.writerow(field_names)
for row in arcpy.SearchCursor(table):
field_vals = []
for field in fieldList:
val = row.getValue(field.name)
# See if it's a geometry field; if so, use WKT
try:
val = val.WKT
except AttributeError:
# It's not a geometry, and that's okay
pass
field_vals.append(val)
w.writerow(field_vals)