Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 比较2个CSV文件,比较时跳过最后一行。有更好的方法吗?_Python_Csv - Fatal编程技术网

Python 比较2个CSV文件,比较时跳过最后一行。有更好的方法吗?

Python 比较2个CSV文件,比较时跳过最后一行。有更好的方法吗?,python,csv,Python,Csv,我有2个csv文件。我正在使用csv dict阅读器 csv1.csv abc,def,ghi abc1,def1,ghi1 abc2,def2,ghi2 csv2.csv abc4,def4,ghi4 abc5,def5,ghi5 abc2,def2,ghi2 其中csv2文件与csv1.csv进行比较。 我必须通过忽略csv2的最后一行来比较两个csv1文件。 csv dict reader中有没有忽略最后一行的方法? 或者,如果列值与特定值匹配,我可以跳过该行吗?一种方法是首先知道cs

我有2个csv文件。我正在使用csv dict阅读器

csv1.csv
abc,def,ghi
abc1,def1,ghi1
abc2,def2,ghi2

csv2.csv
abc4,def4,ghi4
abc5,def5,ghi5
abc2,def2,ghi2
其中csv2文件与csv1.csv进行比较。 我必须通过忽略csv2的最后一行来比较两个csv1文件。 csv dict reader中有没有忽略最后一行的方法?
或者,如果列值与特定值匹配,我可以跳过该行吗?

一种方法是首先知道
csv2
中的行数,然后使用
itertools.islice
切掉最后一行

>>> from itertools import islice
>>> import csv
with open('csv2.csv') as f:
    line_count = sum(1 for _ in f)  #get the line count
    f.seek(0)                       #move the file pointer to the start of the file
    f = islice(f, 0, line_count-1)  #skip last line
    reader = csv.reader(f)         
    print list(reader)
...     
[['abc4', 'def4', 'ghi4'], ['abc5', 'def5', 'ghi5']]

对不起,我还是不太明白你所说的比较行和行差异是什么意思

无论如何,您可以使用以下内容读取第二个csv文件的最后一行以外的所有内容:

import csv

def csv_reader_ignore_last_row(csv_filename):
    with open(csv_filename,'rb') as f:
        reader = csv.reader(f)
        lastrow = reader.next()
        for row in reader:
            yield lastrow
            lastrow = row

for row in csv_reader_ignore_last_row(filename):
    print ', '.join(row)

您可以随时通过调用
reader.next()
next(reader)
跳过
csv.reader
对象中的一行。

比较文件是什么意思?要查找行的差异,请注意:如果您添加了一个比较每个文件中的行的示例,我的回答会更具体。