根据两列中的特定数据比较两个CSV文件
问题描述:
我被鼓励离开我的舒适区,并且使用python,但几乎没有经验,现在我卡住了。我试图比较两个CSV文件(fileA.csv和fileB.csv),并将所有缺少的用户行添加到fileB.csv的fileA.csv中。我可以比较的唯一字段是用户的姓和名(在这种情况下,它是来自每个文件的行[0]和行[2])。根据两列中的特定数据比较两个CSV文件
从我的理解,你不能将信息追加到你目前已经打开的文件,所以我打开建议,而不必创建第三个文件(如果可能)。下面有我在正确的轨道上,但有很多数据,所以我需要一个循环。请帮忙。
import csv
reader1 = csv.reader(open('fileA', 'rb'), delimiter=',', quotechar='|')
row1 = reader1.next()
reader2 = csv.reader(open('fileB', 'rb'), delimiter=',', quotechar='|')
row2 = reader2.next()
##For Loop...
if (row1[0] == row2[0]) and (row1[2] == row2[2]):
## Compare next
else:
## Append entire row to fileA.csv
例FileA.csv:
John,Thomas,Doe,some,other,stuff
Jane, ,Smith,some,other,stuff
例FileB.csv:
John, ,Doe,other,personal,data
Jane,Elizabeth,Smith,other,personal,data
Robin,T,Williams,other,personal,data
应从FILEB追加到FILEA唯一的行知更鸟的完整的行,这样FileA看起来像:
DesiredR esult_FileA:
John,Thomas,Doe,some,other,stuff
Jane, ,Smith,some,other,stuff
Robin,T,Williams,other,personal,data
答
将在文件A中找到的信息先存储在一个存储器中。
然后,重新打开追加模式文件A,并遍历文件B.从乙任何名称不在集合中发现的,可以随后被添加到文件一个:
csv_dialect = dict(delimiter=',', quotechar='|')
names = set()
with open('fileA', 'rb') as file_a:
reader1 = csv.reader(file_a, **csv_dialect)
next(reader1)
for row in reader1:
names.add((row[0], row[2]))
# `names` is now a set of all names (taken from columns 0 and 2) found in file A.
with open('fileA', 'ab') as file_a, open('fileB', 'rb') as file_b:
writer = csv.writer(file_a, **csv_dialect)
reader2 = csv.reader(file_b, **csv_dialect)
next(reader2)
for row in reader2:
if (row[0], row[2]) not in names:
# This row was not present in file A, add it.
writer.writerow(row)
将合并的with
线需要Python 2.7或更高版本。在较早版本的Python,只是窝两种说法:
with open('fileA', 'ab') as file_a:
with open('fileB', 'rb') as file_b:
# etc.
答
您可以尝试pandas,可以帮助你处理CSV文件更容易,而且似乎它更易读:
import pandas as pd
df1 = pd.read_csv('FileA.csv', header=None)
df2 = pd.read_csv('FileB.csv', header=None)
for i in df2.index:
# Don't append if that row is existed in FileA
if i in df1.index:
if df1.ix[i][0] == df2.ix[i][0] and df1.ix[i][2] == df2.ix[i][2]: continue
df1 = df1.append(df2.ix[i])
df1.to_csv('FileA.csv', index=None, header=None)
那是语法是否正确? file_a,打开('fileB','rb')作为file_b: – justin 2013-03-27 10:50:47
@justin:它在Python 2.7中。在早期版本中,只需嵌套两个(因此将它们分隔开来并缩进一级)。 – 2013-03-27 10:51:05
@DSM:感谢您的纠正。 – 2013-03-27 12:03:37