2017-09-14 57 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 
相關問題