Python 提取 Fasta 文件序列 ID 和部分序列并输出
使用 Python 代码提取 Fasta 文件序列 ID 和部分序列并输出
假设我们的 Fasta 文件名为'example.fasta',其格式如下:
seq1 ATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCG
我们需要提取出序列'seq1'的前 20 个碱基,以 Fasta 格式输出:
seq1:1-20 ATCGATCGATCGATCGATCG
下面是对应的 Python 代码实现:
with open('example.fasta', 'r') as f:
lines = f.readlines()
seq_id = lines[0].strip().lstrip('>') # 提取序列 ID,去掉'>'符号
seq = lines[1].strip()[:20] # 提取前 20 个碱基
with open('output.fasta', 'w') as f:
f.write('>{:1-20}
'.format(seq_id)) # 写入新的 Fasta header
f.write(seq + '\n') # 写入序列,保证在一行
代码解释:
- 第 1 行打开 Fasta 文件,读取所有行并存入变量'lines' 中;
- 第 2 行从第 1 行中提取序列 ID,并去掉'>'符号;
- 第 3 行从第 2 行中提取前 20 个碱基;
- 第 5 行打开输出文件'output.fasta',以写入模式打开;
- 第 6 行写入新的 Fasta header,格式为'>seq_id:1-20';
- 第 7 行写入序列,保证在一行。
原文地址: https://www.cveoy.top/t/topic/lMeG 著作权归作者所有。请勿转载和采集!