我正在尝试比较python中的两个csv文件,并将差异保存到python 2.7中的第三个csv文件。
import csv
f1 = open ("olddata/file1.csv")
oldFile1 = csv.reader(f1)
oldList1 = []
for row in oldFile1:
oldList1.append(row)
f2 = open ("newdata/file2.csv")
oldFile2 = csv.reader(f2)
oldList2 = []
for row in oldFile2:
oldList2.append(row)
f1.close()
f2.close()
set1 = tuple(oldList1)
set2 = tuple(oldList2)
print oldList2.difference(oldList1)
我收到错误消息:
Traceback (most recent call last):
File "compare.py", line 21, in <module>
print oldList2.difference(oldList1)
AttributeError: 'list' object has no attribute 'difference'
我是python的新手,一般编码,我还没有完成这个代码(我必须确保将差异存储到变量并将差异写入新的csv文件。)。我一整天都试图解决这个问题而且我根本无法解决这个问题。非常感谢您的帮助。
答案 0 :(得分:1)
差异是什么意思?答案给你两个不同的可能性。
如果所有列相同的行被视为相同,那么您可以通过以下代码获得答案:
import csv
f1 = open ("olddata/file1.csv")
oldFile1 = csv.reader(f1)
oldList1 = []
for row in oldFile1:
oldList1.append(row)
f2 = open ("newdata/file2.csv")
oldFile2 = csv.reader(f2)
oldList2 = []
for row in oldFile2:
oldList2.append(row)
f1.close()
f2.close()
print [row for row in oldList1 if row not in oldList2]
但是,如果某个关键字段(即列)相同,则两行相同,则以下代码将为您提供答案:
import csv
f1 = open ("olddata/file1.csv")
oldFile1 = csv.reader(f1)
oldList1 = []
for row in oldFile1:
oldList1.append(row)
f2 = open ("newdata/file2.csv")
oldFile2 = csv.reader(f2)
oldList2 = []
for row in oldFile2:
oldList2.append(row)
f1.close()
f2.close()
keyfield = 0 # Change this for choosing the column number
oldList2keys = [row[keyfield] for row in oldList2]
print [row for row in oldList1 if row[keyfield] not in oldList2keys]
注意:对于超大文件,上述代码可能运行缓慢。相反,如果您希望通过散列加速代码,则可以在使用以下代码转换set
后使用oldList
:
set1 = set(tuple(row) for row in oldList1)
set2 = set(tuple(row) for row in oldList2)
在此之后,您可以使用set1.difference(set2)
答案 1 :(得分:0)
错误是正确的:元组没有“差异”方法。
我想你想使用set(并使元素不可变)?
set1 = set([tuple(item) for item in oldList1])
set2 = set([tuple(item) for item in oldList2])
答案 2 :(得分:0)
import csv
def read_csv_file(filename):
res = []
with open(filename) as f:
for line in csv.reader(f):
res.append(line)
oldList1 = read_csv_file("olddata/file1.csv")
oldList2 = read_csv_file("olddata/file2.csv")
difference_list = []
for a,b in zip(oldList1,oldList2):
if a != b:
difference_list.append(a + '\t' + b)
最终你有一个项目列表,你可以把它们写到文件中。
编辑: 在这种情况下,[a,b,c] vs [b,c,a]将失败。如果您知道[a,b,c] vs [b,c,a]应该没有返回差异,请使用以下代码。
import csv
def read_csv_file(filename):
res = []
with open(filename) as f:
for line in csv.reader(f):
res.append(line)
oldList1 = read_csv_file("olddata/file1.csv")
oldList2 = read_csv_file("olddata/file2.csv")
difference_list = []
for a in oldList1:
for b in oldList2:
if a != b:
difference_list.append(a + '\t' + b)