Question

So I have managed to now successfully write a python script that will:

Read a CSV file of coordinates written as such:

ID Easting Northing
01 5       5
02 10      10

Then using this:

        x1 = input("What is Easting One?")
        y1 = input("What is Northing One?")
        x2 = input("What is Easting Two?") 
        y2 = input("What is Northing Two?")
        x3 = input("What is Easting Three?")
        y3 = input("What is Northing Three?")
        x4 = input("What is Easting Four?")
        y4 = input("What is Northing Four?")

        print "Your polygon has the bounding coordinates of (x,y): ", (x1,y1), (x2,y2), (x3,y3), (x4,y4)


        polygon = [(y4,x4),(y3,x3),(y2,x2),(y1,x1)]
        trueNum = 0
        falseNum = 0
        for row in a_reader():
            trueOrFalse = point_in_polygon(float(row[2]), float(row[1]),polygon)
            if trueOrFalse == True:
                trueNum = trueNum + 1
            else:
                falseNum = falseNum + 1

Display this:

1 coordinates fall within the polygon
1 coordinates fall outside the polygon 

Now I am able to write a CSV file and output it but I am unsure how to then write a new output CSV file, or even just display it as a list in the shell, so that it would display as.

ID Easting Northing
01 5       5        Inside
02 10      10       Outside

I've been reading other questions/answers but can't find anything to append a new column using a true or false value from within the script.

Was it helpful?

Solution

b_reader = []

for row in a_reader():
    trueOrFalse = point_in_polygon(float(row[2]), float(row[1]),polygon)
    if trueOrFalse == True:
        trueNum = trueNum + 1
        b_reader.append( row.append('Inside'))
    else:
        falseNum = falseNum + 1
        b_reader.append( row.append('Outside'))

And use this b_reader to construct your csv output.

To write to a csv using b_reader (which contains the edits)

for python 3 and above

import csv
with open('output.csv', 'w', newline='') as fp:
    a = csv.writer(fp, delimiter=' ')
    a.writerows(b_reader)

for python 2.7

import csv
fp = open('output.csv', 'wb')
a = csv.writer(fp)
a.writerows(b_reader)
fp.close()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top