我正在尝试编写一段代码,用python打开一个CSV文件,并解析每一行和每一行中的每一个元素。然后查看每个元素是否在另一个CSV文件中,如果是,则将其写入第三个文件。这是我目前的代码,通过测试,我已经确定,我的搜索算法是什么工作不正常
import csv
def generateKnownReport(mypath, GKR):
if GKR==True:
report = open("KnownReport.txt", "w")
file2=frozenset(open("file","r"))
for row in csv.reader(open("file","r"),delimiter=','):
for item in row:
if item in file2:
##report.write(str(row))
print('True')
break
else:
print('ERROR')
report.close()
else:
report = open("KnownReport.txt", "w")
report.write("No Known Report Generated.")
report.close()
任何帮助都将不胜感激。谢谢
你的问题是
if item in file2:
。打开file2
,但不处理它in
不会为您实现搜索。在文件2中搜索item
之前,您至少需要加载文件2唯一合理的方法是将这两个文件读入一个列表或其他iterable中,然后逐步遍历以找出差异
如果重复项不重要,则一个集合将提供更好的性能
以下是一个开始的方法:
相关问题 更多 >
编程相关推荐