【问题标题】:Find Dict Key in File Lines and Append Value on Next Line在文件行中查找字典键并在下一行附加值
【发布时间】:2021-06-16 04:11:19
【问题描述】:

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

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

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

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

#!/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

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    您需要将文本中的数据存储到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)  
    

    【讨论】:

    • 谢谢!这正是我所需要的。非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    相关资源
    最近更新 更多