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

2024-05-19 12:37:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有2个csv文件。我正在使用csv dict reader

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中有没有忽略最后一行的方法? 或者如果列值与特定值匹配,我可以跳过行吗?你知道吗


Tags: 文件csvdefdictreaderabcghicsv1
2条回答

一种方法是先知道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对象的一行。你知道吗

相关问题 更多 >