使用 Python Biopython 库提取 FASTA 文件特定序列

该代码使用 Python Biopython 库从 FASTA 文件中提取特定索引范围内的序列,并将结果保存到新的 FASTA 文件中,保证序列在一行内容。

from Bio import SeqIO

input_file = 'C:/Users/fang/Desktop/合适的程序/序列/M/MC/CP090837.fasta'  # 输入fasta文件名
output_file = 'C:/Users/fang/Desktop/合适的程序/序列/M/MC0/CP090837.fasta'  # 输出fasta文件名
start_index = 1000  # 起始子序列的索引(从0开始)
end_index = 2000  # 结束子序列的索引(包括该索引对应的序列)
selected_records = []  # 存储选择的序列

with open(output_file, 'w') as out_f:
    for i, record in enumerate(SeqIO.parse(input_file, 'fasta')):
        if start_index <= i <= end_index:  # 如果当前序列在选择的索引范围内,则将其存储到selected_records列表中
            selected_records.append(record)
    SeqIO.write(selected_records, out_f, 'fasta-2line')  # 将选择的序列写入到输出文件中,并且保证序列在一行
print('Done.')  # 输出提示信息

代码说明:

  1. 导入 Biopython 库: from Bio import SeqIO
  2. 设置输入和输出文件路径: input_fileoutput_file
  3. 设置起始和结束索引: start_indexend_index
  4. 创建一个列表来存储选择的序列: selected_records
  5. 打开输出文件: with open(output_file, 'w') as out_f:
  6. 遍历输入 FASTA 文件: for i, record in enumerate(SeqIO.parse(input_file, 'fasta')):
  7. 检查索引是否在范围内: if start_index <= i <= end_index:
  8. 将符合条件的序列添加到列表中: selected_records.append(record)
  9. 将选择的序列写入到输出文件,并且保证序列在一行: SeqIO.write(selected_records, out_f, 'fasta-2line')
  10. 输出完成提示: print('Done.')

注意:

  • SeqIO.write() 函数的 format 参数设置为 'fasta-2line' 可以保证序列在一行输出。
  • 该代码假设输入 FASTA 文件中所有序列的长度相同。
  • 确保已安装 Biopython 库:pip install biopython

原文地址: https://www.cveoy.top/t/topic/lMhP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录