我试图将一个csv文件的前300行与另一个csv文件进行比较。我正在迭代第一个文件的每一行。在该迭代中,我迭代第二个文件,计算每次迭代,直到找到匹配。然后我将计数值(第二个文件中匹配行的行)输出到文本文件中。
这是我到目前为止所做的:
import csv
with open('/Volumes/cachannel/CUTLER/subsampling/in-silico_IDC18_GFP18_names_only.csv', 'rb') as file1:
file1reader = csv.reader(file1)
with open('/Volumes/cachannel/CUTLER/subsampling/ICD18_GFP18_names_only.csv', 'rb') as file2:
file2reader = csv.reader(file2)
header1 = file1reader.next()
header2 = file2reader.next()
count = 0
with open("Rank_results.txt", 'a') as outfile:
while count < 300:
print(count)
for line1 in file1reader:
linenum = 1
for line2 in file2reader:
if line1 == line2:
print('match found')
outfile.write(str(linenum))
else:
linenum += 1
count += 1
我现在得到的错误是它只找到第一场比赛而没有找到任何其他比赛 - 当我知道还有更多时。
这里要清楚的是一个例子:
文件1:
Bob
Sue
Sally
Herald
文件2:
Sue
Bob
Herald
Sally
输出文件:
2 1 4 3
答案 0 :(得分:1)
您的主要问题是尝试多次迭代第二个文件。为了不止一次迭代其整个内容,您需要关闭并重新打开它。您还可以让Python使用enumerate()
自动计算行号,并通过将匹配数存储在列表中并检查其长度来计算匹配数。
另一个问题是示例输入文件中没有标题行。假设它们确实包含它们,以下应该做你想要的:
import csv
MAX_COUNT = 300
filename1 = '/Volumes/cachannel/CUTLER/subsampling/in-silico_IDC18_GFP18_names_only.csv'
filename2 = '/Volumes/cachannel/CUTLER/subsampling/ICD18_GFP18_names_only.csv'
matches = []
with open(filename1, 'rb') as file1:
file1reader = csv.reader(file1)
header1 = file1reader.next()
for line1 in file1reader:
with open(filename2, 'rb') as file2:
file2reader = csv.reader(file2)
header2 = file2reader.next()
for linenum, line2 in enumerate(file2reader, start=1):
if line1 == line2:
print('match found')
matches.append(str(linenum))
if len(matches) >= MAX_COUNT:
break
if len(matches) >= MAX_COUNT:
break
with open("Rank_results.txt", 'w') as outfile:
outfile.write(' '.join(matches) + '\n')