我试图比较一个csv文件的前300行和另一个。我正在迭代第一个文件的每一行。在该迭代中,我将遍历第二个文件,计数每个迭代,直到找到匹配的。然后,我将计数值(第二个文件中匹配行的行)输出到文本文件中。
以下是我到目前为止所拥有的:
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发布于 2016-06-06 23:54:50
您的主要问题是尝试多次迭代第二个文件。为了多次遍历整个内容,您需要关闭并重新打开它。您还可以让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')https://stackoverflow.com/questions/37667696
复制相似问题