使用python将csv文件的一行中的列值与下一行中的值进行比较

时间:2017-09-14 20:14:26

标签: python-2.7 csv

我接下来一直在阅读csv.reader,但是没有找到比较一行中一行到下一行的值的方法。例如,如果我的数据在Maps.csv文件中显示如下:

County1     C:/maps/map1.pdf 
County1     C:/maps/map2.pdf 
County2     C:/maps/map1.pdf 
County2     C:/maps/map3.pdf 
County3     C:/maps/map3.pdf 
County4     C:/maps/map2.pdf 
County4     C:/maps/map4.pdf

如果第二行的县等于第一行的县做某事

以下代码比较行,我想比较当前行和上一行之间的县值。

import csv.

f = open("Maps.csv", "r+")
ff = csv.reader(f)

pre_line = ff.next()
while(True):
    try:
        cur_line = ff.next()
        if pre_line == cur_line:
            print "Matches"
        pre_line = cur_line
    except:
        break

我知道我可以获取当前值(见下文),但不知道如何获取以前的值。这可能吗?如果是这样,有人可以告诉我如何。在第三天尝试解决编写我的脚本从csv文件追加pdf文件,并准备把我的咖啡杯扔在我的显示器上。我将这些分解为更小的部分并使用更简单的数据作为试点。我的文件要大得多。我被建议在发布到这个论坛时只关注一个问题。这是我最近的一期。似乎无论我采取什么样的措施,我似乎都无法按照我想要的方式阅读数据。 Arrrggghhhhh。

CurColor = row[color]

使用python 2.7

2 个答案:

答案 0 :(得分:0)

您已经知道如何查找上一行。为什么不从该行获取所需的列?

import csv.

f = open("Maps.csv", "r+")
ff = csv.reader(f)

pre_line = ff.next()
while(True):
    try:
        cur_line = ff.next()
        if pre_line[0] == cur_line[0]: # <-- compare first column
            print "Matches"
        pre_line = cur_line
    except:
        break

或更简单:

pre_line = ff.next()
for cur_line in ff:
    if pre_line[0] == cur_line[0]: # <-- compare first column
        print "Matches"
    pre_line = cur_line

答案 1 :(得分:0)

import csv

f = open("Maps.csv", "r+")
# Use delimiters to split each line into different elements
# In my example i used a comma. Your csv may have a different delimiter
# make sure the delimiter is a single character string though
# so no multiple spaces between "County1     C:/maps/map1.pdf"
# it should be something like "County1,C:/maps/map1.pdf"
ff = csv.reader(f, delimiter=',')

COUNTY_INDEX = 0

# each time ff.next() is called, it makes an array variable ['County1', 'C:/maps/map1.pdf ']
# since you want to compare the value in the first index, then you need to reference it like so
# the line below will set pre_line = 'County1'
pre_line = ff.next()[COUNTY_INDEX]
while(True):
    try:
        # the current line will be 'County1' or 'County2' etc...Depending on which line is read
        cur_line = ff.next()[COUNTY_INDEX]
        if pre_line == cur_line:
            print "Matches"
        pre_line = cur_line
    except:
        break