我正在尽力解决以下问题:
我想将2个文件(file1.txt和file2.txt)相互比较。第一个文件(file1.txt)包含字典(字符串)。它们用于搜索第二个文件(file2.txt)。如果在file2.txt中找到相同的字符串,则应将其删除。这应该遍历file1中的所有字符串。
我正在使用以下代码:
import csv
import os
enter code here
crimefile = open('file1.txt', 'r')
reader = csv.reader(crimefile)
allRows = [row for row in reader]
crimefileB = open('file2.txt', 'r')
reader = csv.reader(crimefileB)
allRowsB = [row for row in reader]
for counter in xrange(0,allRowsB.count()):
print count
if allRows[count] == allRowsB[count]: allRowsB[count-2].remove
enter code here
在附加的代码中,我将它们导出到列表中,但我不想在此方法中执行任务。
非常感谢任何帮助。
答案 0 :(得分:0)
您可以执行以下操作:
import csv
import os
crimefile = open('file1.txt', 'r')
reader = csv.reader(crimefile)
# Sets are much faster for membership checks. Also, using a generator
# (the ()'s) instead of a list will save memory, as the entire file will
# not need to loaded in all at once.
filtervals = set((row for row in reader))
out = []
crimefileB = open('file2.txt', 'r')
reader = csv.reader(crimefileB)
for line in reader:
if line not in filtervals:
out.append(line)
# Don't forget to close the files you open!
out
将包含由file1.txt过滤的file2.txt。
你也可以做最后一点作为列表理解。
out = [ line for line in reader if line not in filtervals ]