Python 使用 Biopython 库提取 FASTA 文件特定序列
使用 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.') # 输出提示信息
代码说明:
- 导入 Biopython 库:
from Bio import SeqIO - 设置输入和输出文件路径:
input_file和output_file - 设置起始和结束索引:
start_index和end_index - 创建一个列表来存储选择的序列:
selected_records - 打开输出文件:
with open(output_file, 'w') as out_f: - 遍历输入 FASTA 文件:
for i, record in enumerate(SeqIO.parse(input_file, 'fasta')): - 检查索引是否在范围内:
if start_index <= i <= end_index: - 将符合条件的序列添加到列表中:
selected_records.append(record) - 将选择的序列写入到输出文件,并且保证序列在一行:
SeqIO.write(selected_records, out_f, 'fasta-2line') - 输出完成提示:
print('Done.')
注意:
SeqIO.write()函数的format参数设置为'fasta-2line'可以保证序列在一行输出。- 该代码假设输入 FASTA 文件中所有序列的长度相同。
- 确保已安装 Biopython 库:
pip install biopython
原文地址: https://www.cveoy.top/t/topic/lMhP 著作权归作者所有。请勿转载和采集!