Take the 2-minute tour ×
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
f.close()

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

Any advice would be very much appreciated!

Thanks!

share|improve this question
5  
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
3  
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

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

 
discard

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.