how to output coordinate values of feature class to text file

893 views Asked by At

In the database there is list of feature classes. the codes below can successfully print the x, y of each point of each feature in the feature class. the comment part # is not working, and I dont know how to write the coordinate values of the points to a text file.

arcpy.env.workspace = 'database'
fc='file1'
outpath='output Directory' 
cursor=arcpy.da.SearchCursor(fc, ["OID@","SHAPE@"])
#output=open("result.txt","w")
for row in cursor: #iterate the rows in the table
    print ("Feature {0}: ".format(row[0]))
    for point in row[1].getPart(0):
        print ("{0},{1}".format(point.X, point.Y))  
        #output.write(str(point.X)+""+str(point.Y)+"\n")
        #read_data = output.read()
        #print read_data
#output.close()

Any help is appreciated !

the new codes look like:

arcpy.env.workspace = 'database'
fc='file1'
outpath='output Directory' 
cursor=arcpy.da.SearchCursor(fc, ["OID@","SHAPE@"])
with open('result.txt', 'w') as output:
    for row in cursor: #iterate the rows in the table
        for point in row[1].getPart(0):
            output.write(str(point.X)+""+str(point.Y)+"\n")
            print os.path.isfile('result.txt')
output.close()
1

There are 1 answers

12
erhesto On

Okay, I checked this with my own python session, and apparently the way to write something to file is .close() it after work. Uncomment your code and write:

output.close()

...after it. Somehow, even better way to work with files (according to python's documentation) is using with statement:

>>> with open('workfile', 'r') as output:
...     read_data = output.read()
>>> output.closed
True

In your case, write your code below "with open" at indented place. Hope it helped.

Edit: This with statement above is just an example from python's documentation. In your case I suggest trying:

arcpy.env.workspace = 'database'
fc='file1'
cursor=arcpy.da.SearchCursor(fc, ["OID@","SHAPE@"])
with open('result.txt', 'w') as output:
    for row in cursor: #iterate the rows in the table
        print ("Feature {0}: ".format(row[0]))
        for point in row[1].getPart(0):
            print ("{0},{1}".format(point.X, point.Y))  
            output.write(str(point.X)+""+str(point.Y)+"\n")