Sign up ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I am trying desperately to grab records in a shapefile's attribute table and copy them, with additional formatting to a txt file. Below is the code I have developed thus far:

I have used the following post (Using SearchCursor to access & export values in a raster table) for guidance but for some reason python has issues with my declared output file, f.

# Import arcpy and the SeachCursor function

import arcpy
# Find the target shapefile in memory
shapefile = "C:/Users/user/Dropbox/CE 691/GI/GISData/ExampleEPANETNetwork.mdb/Nodes"

# Create the Text File to write the Indicated Values
f = open("C:/Users/user/Desktop/test.txt", "w")

# Use SearchCursor to Identify the necessary fields
find_junction = arcpy.SearchCursor(shapefile, "", "",  "Elevation;Demand;X_Coord;Y_Coord","")

# Convert Found Field to Text and Place in Text File
for row in find_junction:
    get_elevation = row.getValue("Elevation")
    get_demand = row.getValue("Demand")
    get_x_coord = row.getValue("X_Coord")
    get_y_coord = row.getValue("Y_Coord")
    print get_elevation, get_demand, get_x_coord, get_y_coord
    f.write(str(get_elevation + "    " + get_demand + "    " + get_x_coord + "    " + get_y_coord)

# Close the output text file

# Delete all variables utilized
del find_junction, get_elevation, get_demand, get_x_coord, get_y_coord

Any advice would be very much appreciated!


share|improve this question
f.write is missing a closing parentheses. You may want to include the error message and line number. –  klewis Mar 4 '13 at 2:03
You'll also probably want to add a linefeed (+ "\n") at the end of your line. Also, consider instead using the csv module which makes this type of file writing much cleaner. –  blah238 Mar 4 '13 at 2:12
Although this not the problem you declare a variable called shapefile but it's actually a personal geodatabase FeatureClass. Shapefiles and personal geodatabases have different SQL syntax and storage capabilities. So calling it "shapefile" is misleading and makes potential debugging difficult. You will often see in code examples the input simply called "fc" for featureclass, much more generic. –  Hornbydd Sep 12 at 17:14

1 Answer 1

Type cast each variable to string type before writing to file, as f.write() take string parameter only.

your code:

f.write(str(get_elevation + "    " + get_demand + "    " + get_x_coord + "    " + get_y_coord))

Change to

f.write(str(get_elevation) + "    " + str(get_demand) + "    " + str(get_x_coord) + "    " + str(get_y_coord) + "\n")

Apart from this line, every thing is fine in your script

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.