Python:比较两个csv文件中的特定列 [英] Python: Comparing specific columns in two csv files

查看:1168
本文介绍了Python:比较两个csv文件中的特定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个CSV文件(file1和file2),内容如下所示:

Say that I have two CSV files (file1 and file2) with contents as shown below:

file1:

fred,43,Male,"23,45",blue,"1, bedrock avenue"

file2:

fred,39,Male,"23,45",blue,"1, bedrock avenue"

我想比较这两个CSV记录,看看列0 ,2,3,4和5是相同的。我不在乎第1列。

I would like to compare these two CSV records to see if columns 0,2,3,4, and 5 are the same. I don't care about column 1.

这是最python的方式是什么?

What's the most pythonic way of doing this?

EDIT:

部分示例代码将不胜感激。

Some example code would be appreciated.

/ strong>

请注意,内嵌的逗号需要正确处理。

Please note the embedded commas need to be handled correctly.

推荐答案

我想最好的方法是使用Python库: http://docs.python.org/library/csv.html

I suppose the best ways is to use Python library: http://docs.python.org/library/csv.html.

UPDATE(添加示例)

import csv
reader1 = csv.reader(open('data1.csv', 'rb'), delimiter=',', quotechar='"'))
row1 = reader1.next()
reader2 = csv.reader(open('data2.csv', 'rb'), delimiter=',', quotechar='"'))
row2 = reader2.next()
if (row1[0] == row2[0]) and (row1[2:] == row2[2:]):
    print "eq"
else:
    print "different"

这篇关于Python:比较两个csv文件中的特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆