2017-09-14 191 views
0

我一直在阅读csv.reader,但未看到将列中的值从一行比较到下一个。举例来说,如果我的数据看起来像这样在Maps.csv文件:使用python将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

+0

刚刚看了你的CSV文件导入行的列表:'行=名单(FF)'。现在你将内存中的整个csv作为lsts列表 –

回答

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 
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 
相关问题