在python中格式化文本文件

时间:2016-07-18 20:26:04

标签: arcpy

这是我的代码:

import arcpy
arcpy.env.workspace = "C:\Users\Brett\Desktop\lesson_6\Lesson6_Data"
infc = "Cities.shp"

outputFile =   open("C:\Users\Brett\Desktop\lesson_6\Lesson6_Data\Output_Cities1.txt", "w")      

arcpy.GetParameterAsText(0)

fc = "Cities.shp"
fields = ["NAME","SHAPE@XY"]

with arcpy.da.SearchCursor(fc, fields) as cursor:
for row in cursor:
    outputFile.write('{0}, {1}'.format(row[0],(row[1])))

print "done"

这就是输出格式的样子:

Hiawatha,( - 1050316.3479999993,2067521.4093999993)Powder Wash,( - 1025371.6007000003,2059421.7783000004)Kings Canyon,( - 852695.0120999999,2036738.5595999993)Columbine,( - 915047.0152000003,2035509.35099999

但我希望它看起来像这样:

FredRanch1_1, 529018.125025, 4108038.05548
FredRanch1_1, 529005.718792, 4108028.20659
FredRanch1_1, 528993.340503, 4108018.73931
FredRanch1_1, 528980.990158, 4108009.65364
FredRanch1_1, 528968.667757, 4108000.94958

等...

有关如何格式化的任何建议都是正确的吗?

2 个答案:

答案 0 :(得分:1)

SHAPE@XY返回一个值元组,您可以通过它们的索引位置访问它们。您可以通过将\n添加到该行的末尾来为每条记录添加换行符。

for row in cursor:
    outputFile.write('{0}, {1}, {2}\n'.format(row[0], row[1][0], row[1][1]))

答案 1 :(得分:0)

这帮助我把它排成一行

以 arcpy.da.SearchCursor(fc, fields) 作为光标: 对于游标中的行: COFile.write(u'{0}, {1}'.format(row[0], row[1])+ "\n") COFile.close() 打印(“完成”)