0

我有 2 个输入文件,input.txt并且datainput.txt. 我检查第 2 列是否input.txt与 的第 1 列datainput.txt匹配,如果匹配,则将其放在orthodb_id输出文件中相关行的末尾。

输入.txt:

5 21 218
6 11 1931
7 26 173

数据输入.txt:

>21|95|28|5
Computer
>11|28|5|5
Cate 

代码.py:

import csv

with open('input.txt', 'rb') as file1:
    file1_data = dict(line.split(None, 2)[1::-1] for line in file1 if line.strip())

with open('data.txt', 'rb') as file2, open('output.txt', 'wb') as outputfile:
    output = csv.writer(outputfile, delimiter='|')
    for line in file2:
        if line[:1] == '>':
            row = line.strip().split('|')
            key = row[0][1:]
            if key in file1_data:
                 output.writerow(row + [file1_data[key]])

这是我的代码得到的输出:

>21|95|28|5|5
>11|28|5|5|6
4

1 回答 1

1

您只需else在代码中添加一个块即可获得所需的输出:

import csv

with open('input.txt', 'rb') as file1:
    file1_data = dict(line.split(None, 2)[1::-1] for line in file1 if line.strip())

with open('data.txt', 'rb') as file2, open('output.txt', 'wb') as outputfile:
    output = csv.writer(outputfile, delimiter='|')
    for line in file2:
        if line[:1] == '>':
            row = line.strip().split('|')
            key = row[0][1:]
            if key in file1_data:
                output.writerow(row + [file1_data[key]])
        else:
            outputfile.write(line)
于 2013-03-31T20:21:41.697 回答