How do I create and write to a new text or excel file?

559
3
01-31-2011 11:47 AM
GaryEhrhardt
New Contributor II
I've written a python script that loops thru all records in a shapefile, checks each record for certain criteria and prints out certain fields from the records that meet the condition. That is working fine. Now instead of printing the results, I want to write these certain fields to either a text file or an excel file. Any suggestions on what commands or simple block of code might accompliss this?

Here is my script that prints my results:

import arcpy

from arcpy import env
env.workspace = "C:/workspace"
pin_hold = "999999999999"
area_hold = 0
township_hold = ""
section_hold = ""
quarter_hold = ""
parcelname_hold = ""
public_hold = ""
corrsource_hold = ""

text_file = open("rename_pins.txt", "w")
rows = arcpy.SearchCursor("parcels_Identity6.SHP", "", "", "", "PIN; PARCELNAME; BLMPIN; TRANSFER; PUBLIC_; PARCEL_KEY; CORR_SOURC; Shape_area; Shape_len; Id; Township; Section; Quarter", "PIN A")

for row in rows:
    if row.PIN == pin_hold:
        if row.Shape_area > area_hold:
            area_hold = row.Shape_area
            township_hold = row.Township
            section_hold = row.Section
            quarter_hold = row.Quarter
            parcelname_hold = row.PARCELNAME
            public_hold = row.PUBLIC_
            corrsource_hold = row.CORR_SOURC
    else:
        if pin_hold[0:4] != township_hold or pin_hold[4:6] != section_hold or pin_hold[6] != quarter_hold:
            print pin_hold + ' ' + str(area_hold) + ' ' + parcelname_hold + ' ' + public_hold + ' ' + corrsource_hold
        pin_hold = row.PIN
        area_hold = row.Shape_area
        township_hold = row.Township
        section_hold = row.Section
        quarter_hold = row.Quarter
        parcelname_hold = row.PARCELNAME
        public_hold = row.PUBLIC_
        corrsource_hold = row.CORR_SOURC

print 'completed'

Thanks,
Gary
Tags (2)
0 Kudos
3 Replies
RobinWilson
New Contributor
In this case I'd suggest writing to CSV (comma separated values) files, as they can easily be read both as text files and in Excel (and other spreadsheet packages). As for how to write them in Python, there are a number of options:

You could simply write the data using the standard text file writing python commands (see http://snipplr.com/view/6630/reading-and-writing-text-files-in-python/ for a simple tutorial) and put comma's between them. For example, I used the following code in one of my projects:

# Open the file
FILE = open(output_file, "a")
# Write the header (so I can remember what each column is!)
FILE.write("name,n,mean_len,total_len,max_len,min_len,stdev_len,mean_closeness,std_closeness,defect_dens,r_score,z_score,p_value\n")
# Get the line that I need to write to the CSV file (it is returned from a function I wrote to do my processing)
csv_line = process_file(full_path)
# Print it to the screen (just for testing really)
print csv_line
# Write it to the file
FILE.write(csv_line + "\n")
# Close the file
FILE.close()


Of course, I also had some code within the process_file() function which created the line of CSV to write:

# Put all of the statistics into a list - in this case all of the items in the list are variables that I have calculated
output_stats = [tidied_file_name, n_dunes, mean_len, total_len, max_len, min_len, stdev_len, mean_closeness, std_closeness, defect_dens, r_score, z_score, p_value]
    # For each of the items in this list, convert it to a string and append to an array
    for item in output_stats:
        csv_array.append(str(item))

    # Join this array, adding commas between all the items
    csv_string = ",".join(csv_array)
    # Return this comma joined array ready to write to the file
    return csv_string


The alternative is to use a Python library like the CSV library (http://docs.python.org/library/csv.html) which comes with functions to read and write CSV files.

Hope that helps,

Robin
0 Kudos
by Anonymous User
Not applicable
My simple method of writing a list.

def writefile(file, list):
  f = open(file,"w")
  f.write("EASTING, NORTHING, READING\n")
  for record in list:
    f.write("%i, %i, %s\n" % (record[0],record[1],record[2]))
  f.close()
  return
0 Kudos
GaryEhrhardt
New Contributor II
Thanks to Robin and Huey for your quick responses. I went with the CSV approach and it worked great.
0 Kudos