Writing shapefile field values to txt file using SearchCursor?

I'm having trouble finding a way to write the output of a SearchCursor function to a txt. file. I can print it just fine in a format that is desirable. I just don't know how to get from there to a txt. file. Here's my code below:

import arcpy from arcpy import env env.workspace = "G:Geocomputation_ProjectSection CLin_Ref_test" shape = "Points.shp" cursor = arcpy.SearchCursor(shape) f = open("test_field.txt", "w") for row in cursor: print (row.getValue("ITEMID")),(row.getValue("New_X_LRR")), (row.getValue("New_Y_LRR")) print "done"

The txt file does not yet exist. When I start running this script, I hope to be able to overwrite the text file as I do more iterations.

I am using ArcMap 10.2.2

I inserted the lines you require in between:

import arcpy import os from arcpy import env env.workspace = r"G:Geocomputation_ProjectSection CLin_Ref_test" # Delete prior output if it exists # Insert a line that creates a variable for the text file try: os.remove("C:	empoutput1.txt") except OSError: pass print("output1.txt deleted") outtext = r'C:	empoutput1.txt' # here supply your path and filename # Then your code shape = "Points.shp" cursor = arcpy.SearchCursor(shape) openfile = open(outtext, 'a') for row in cursor: print row.getValue("ITEMID"), row.getValue("New_X_LRR"), row.getValue("New_Y_LRR") # Then out put the stuff you want to print into the text file # (I used new line here you can change how you can concatenate # the rows. For example if you want to join them with a ',' # then change the '
' part into ','.) openfile.write( str(row.getValue("ITEMID")) +"+ str(row.getValue("New_X_LRR")) +"+ str(row.getValue("New_Y_LRR")) + '
' ) print "done" openfile.close()

I've found an efficient pythonic if exists line from the accepted answer here credit for that goes to SE user Matt

Watch the video: QGIS Python PyQGIS - Calculate Field Values Field Calculator (October 2021).