2

I am solving a location-allocation type of problem where I use a loop to go through several specifications of the problem. The model runs fine, and produces the vizualization outputs just as expected.

enter image description here

At the end of each run I try to append the values from one of the resulting tables to a .txt file using the following script in "Export". The script writes to the file but each time the For loop runs, it overwrites the file instead of appending despite the specification of the code. If I open half-way through the processing I can see the results getting deleted and updated straight after. Can you help me figuring out what is wrong?

import arcpy, csv

table = arcpy.GetParameterAsText(0)
outfile = arcpy.GetParameterAsText(1)

#List of all of the fields in the table
fields = arcpy.ListFields(table)
field_names = [field.name for field in fields]

with open(outfile,'ab') as f:
    w = csv.writer(f)

    #Search cursor that will iterate through the rows of the table
    for row in arcpy.SearchCursor(table):
        field_vals = [row.getValue(field.name) for field in fields]
        w.writerow(field_vals)

FINAL EDIT: I have followed the suggestions and changed my model and my script code as below. Now everything works as expected.

enter image description here

import arcpy

outfile = arcpy.GetParameterAsText(0)
bays = arcpy.GetParameterAsText(1)
service = arcpy.GetParameterAsText(2)

with open(outfile,'a') as f:
    f.write(bays + "," + service + "\n")
  • Are you really running ArcGis 9.3? It appears from stackoverflow.com/questions/21432610/… that it could be field_vals = [[row.getValue(field.name) for field in fields]] ... a list of list of values. Are you writing your field names to the CSV file? I see you are getting them but not actually using them, I suspect that you've removed that part to post. There are fields that don't want to be exported (like shape) which you should skip. – Michael Stimson Dec 19 '14 at 5:02
  • Just a guess-remove output to text.txt from the model or make it an input parameter. Script takes 2 and does the job. – FelixIP Dec 19 '14 at 9:47
  • @FelixIP can you clarify your suggestion? I need the Output to text.txt in order to append the new Facilities statistics to a text file. – André Alho Dec 19 '14 at 15:07
  • @Michael Miles-Stimson, I have cleaned up the code. I am not writing the field names to the CSV file, just using them to iterate over the columns and collect the row values. The are only three fields, ObjectID, a Count and a Sum field so no issues with "shape". – André Alho Dec 19 '14 at 15:09
  • Solved. Updated the post. – André Alho Dec 19 '14 at 16:15

Browse other questions tagged or ask your own question.