首页 > 解决方案 > 在文件行中查找字典键并在下一行附加值

问题描述

我有一本由键和值组成的字典。键对应于物种名称,值对应于 DNA 序列。我想读取另一个文件的行,当找到我的字典中的键时,将其值附加到文件的下一行。

我遇到的问题是我所有的值都附加到文件的底部。这似乎应该是一件非常简单的事情,但我不知道该怎么做。

我已经搜索了一个没有运气的解决方案,所以我很感激可能提供的任何帮助。

这是我正在使用的代码示例:

#!/usr/bin/env python3

import os

file_being_read = "path_to_file"

dict_speciesNAME_dnaSEQ = {'species1':'dna_seq1', 'species2':'dna_seq2', 'species3':'dna_seq3'}

for lines in open(file_being_read, 'r'):
    for k,v in dict_speciesNAME_dnaSEQ.items():
        with open(file_being_read, 'a') as outfile:
            if k in lines:
                outfile.write(v)

file_being_read 的行:

>Seq1 species1
>Seq2 species3
>Seq3 species2

我的代码的输出:

>Seq1 species1
>Seq2 species3
>Seq3 species2
dna_seq1
dna_seq3
dna_seq2

期望的输出:

>Seq1 species1
dna_seq1
>Seq2 species3
dna_seq3
>Seq3 species2
dna_seq2

标签: pythonpython-3.x

解决方案


您需要将文本中的数据存储到 a 中list,然后在处理后将其写list回文件

前任:

file_being_read = "path_to_file"

dict_speciesNAME_dnaSEQ = {'species1':'dna_seq1', 'species2':'dna_seq2', 'species3':'dna_seq3'}

result = []
with open(file_being_read, 'r') as infile:
    for line in infile:
        result.append(line)
        for k,v in dict_speciesNAME_dnaSEQ.items():
            if k in line:
                result.append(v+"\n")

# Write Back to File
with open(file_being_read, 'w') as outfile:
      for line in result:
          outfile.write(line)  

推荐阅读