Python 2.7 使用python将csv文件的一行中的列中的值与下一行中的值进行比较
我一直在阅读csv.reader next,但没有找到一种方法将列中的值从一行比较到下一行。例如,如果我的数据在Maps.csv文件中如下所示:Python 2.7 使用python将csv文件的一行中的列中的值与下一行中的值进行比较,python-2.7,csv,Python 2.7,Csv,我一直在阅读csv.reader next,但没有找到一种方法将列中的值从一行比较到下一行。例如,如果我的数据在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.pd
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文件的问题,我正要把咖啡杯扔到显示器上。我将这些数据分解成更小的部分,并使用更简单的数据作为试点。我的档案要大得多。有人建议我在论坛上发帖时一次只关注一个问题。这是我的最新一期。似乎无论我采取什么策略,我都无法以我想要的方式读取数据。啊
CurColor = row[color]
使用python 2.7,您已经知道如何查找前一行。为什么不从该行获取所需的列
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
只需将csv文件读入行列表:rows=listf。现在,整个csv作为LST列表存储在内存中
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