读取并输出true或false后,将新列附加到csv

时间:2014-05-10 08:08:07

标签: python csv append output

所以我现在成功地编写了一个python脚本:

读取这样写的坐标的CSV文件:

ID Easting Northing
01 5       5
02 10      10

然后用这个:

        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

显示:

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

现在我能够编写一个CSV文件并输出它,但我不确定如何编写新的输出CSV文件,或者甚至只是将其显示为shell中的列表,以便它显示为。

ID Easting Northing
01 5       5        Inside
02 10      10       Outside

我一直在阅读其他问题/答案,但找不到任何可以在脚本中使用true或false值附加新列的内容。

1 个答案:

答案 0 :(得分:0)

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'))

并使用此b_reader构建csv输出。

使用b_reader(包含编辑内容)写入csv

for python 3及以上

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()