【问题标题】:How iterate through fasta files and modify the record id using Biopython如何使用 Biopython 遍历 fasta 文件并修改记录 id
【发布时间】:2014-03-27 18:31:57
【问题描述】:

我不是程序员,我是 Python 新手,我正在尝试自学...所以,我有一个包含 84 个条目的文件,如下所示:

1
2
3
X
Y
MT
GL000210.1

我想更改包含 84 条记录的 fasta 文件中所有序列的记录 ID。下面是一个fasta文件的例子:

>name
agatagctagctgatcgatcgatttttttcga
>name1
gagatagatattattttttttttaagagagagcgcgatcgatgc
>name2
agatgctagggc
...

具体来说,我想通过上面示例文件的第一个条目更改第一个记录 ID(以“>”开头),依此类推。到目前为止,我创建了以下脚本。我可以一个一个地更改 id,但我不知道同时遍历两个文件:

from Bio import SeqIO

records = list(SeqIO.parse("new_human_v37.fasta", "fasta"))
modified_record = records[0]
print(modified_record.id.replace("old_name", "first_entry_file1"))

输出文件应如下所示:

>1
agatagctagctgatcgatcgatttttttcga
>2
gagatagatattattttttttttaagagagagcgcgatcgatgc
>3
agatgctagggc
...

有人可以帮忙吗?

【问题讨论】:

    标签: python loops biopython fasta


    【解决方案1】:

    您可以这样做(假设第一个文件与第二个文件的行数相同)。如果你想用修改后的记录生成一个新文件。

    from Bio import SeqIO
    lines_file = open(my_lines_file, 'r')
    fout = open("example.fa", "w")
    records = list(SeqIO.parse("new_human_v37.fasta", "fasta"))
    
    for r in records:
        line = lines_file.getline()
        r.id = line.rstrip()
        SeqIO.write(fout, r, 'fasta')
    
    
    lines_file.close()
    fout.close()
    

    【讨论】:

      【解决方案2】:

      试试这个。

      # first create a new file to write into ex: "fasta_file_new.fasta"
      # then run the code
      fasta_file_new = open("fasta_file_new.fasta", "w")
      fasta_file_read = open("new_human_v37.fasta", "r")
      replace_lines = open("replacer.txt", "r")
      
      
      for f in fasta_file_read.readlines():
          if f.__contains__(">"):
              fasta_file_new.write(">" + replace_lines.readline())
          else:
              fasta_file_new.write(f)
      
      
      fasta_file_new.close()
      fasta_file_read.close()
      replace_lines.close()
      

      【讨论】:

      • 您应该在代码示例中加上解释为什么会这样以及可能出现的其他问题(如果有的话)。仅添加代码不足以使答案有用。
      • @O.D.P 好的,我了解您是如何做到的(readline 与 readlines)。我试过了,效果很好。感谢大家的帮助。
      • Apesa,很高兴知道。这是我在 SO 上的第一篇文章,所以我只是在学习协议。
      • FRANK_B - 没问题,为这个网站提供帮助和贡献很有趣。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      相关资源
      最近更新 更多