Python代码合并多个fasta序列文件
以下是用Python代码合并一个文件夹下多个fasta序列文件的示例代码:
import os
# 定义函数,读取fasta文件,返回序列和标题
def read_fasta(file):
seq = ''
title = ''
with open(file, 'r') as f:
for line in f:
if line.startswith('>'):
title = line.rstrip()
else:
seq += line.rstrip()
return title, seq
# 定义函数,将多个fasta序列文件合并成一个文件
def merge_fasta_files(folder_path, output_file):
# 获取文件夹下所有fasta文件
files = [f for f in os.listdir(folder_path) if f.endswith('.fasta')]
# 打开输出文件
with open(output_file, 'w') as out:
# 遍历所有fasta文件,读取序列并写入输出文件
for file in files:
title, seq = read_fasta(os.path.join(folder_path, file))
out.write(title + '\n')
out.write(seq + '\n')
# 测试代码
if __name__ == '__main__':
folder_path = 'fasta_files'
output_file = 'merged.fasta'
merge_fasta_files(folder_path, output_file)
该代码中,read_fasta函数用于读取fasta文件,返回序列和标题。merge_fasta_files函数用于将多个fasta序列文件合并成一个文件。该函数首先获取文件夹下所有fasta文件,然后遍历所有文件,读取序列并写入输出文件。最后,测试代码通过调用merge_fasta_files函数将fasta文件夹中的所有fasta序列文件合并成一个文件merged.fasta。
原文地址: https://www.cveoy.top/t/topic/lMdr 著作权归作者所有。请勿转载和采集!