comparison gbk2fa.py @ 10:5b4ac70948d2 draft

planemo upload for repository https://github.com/galaxyproject/tools-iuc/tree/master/tool_collections/snpeff commit eea43430ff90fe6b13b295f6d5efb2208401a7ef
author iuc
date Tue, 27 Mar 2018 09:44:18 -0400
parents
children 479c4f2f4826
comparison
equal deleted inserted replaced
9:68693743661e 10:5b4ac70948d2
1 import argparse
2 import bz2
3 import contextlib
4 import gzip
5 import sys
6
7 import magic
8 from Bio import SeqIO
9
10 parser = argparse.ArgumentParser()
11 parser.add_argument("genbank_file", help="GenBank input file. Can be compressed with gzip or bzip2")
12 parser.add_argument("fasta_file", help="FASTA output datset")
13 parser.add_argument("--remove_version", dest="remove_version", action="store_true", help="Remove version number from NCBI form formatted accession numbers. For example, this would convert 'B000657.2' to 'B000657'")
14 args = parser.parse_args()
15
16 gbk_filename = args.genbank_file
17 fa_filename = args.fasta_file
18
19
20 @contextlib.contextmanager
21 def get_file_handle(gbk_filename):
22 f_type = magic.from_file(args.genbank_file, mime=True)
23 if f_type == 'text/plain':
24 input_handle = open(gbk_filename, "r")
25 elif f_type == 'application/gzip':
26 input_handle = gzip.open(gbk_filename, "rt")
27 elif f_type == 'application/x-bzip2':
28 input_handle = bz2.open(gbk_filename, "rt")
29 else:
30 sys.exit("Cannot process file of type {}. Only plain, gzip'ed, and bzip2'ed genbank files are accepted ".format(f_type))
31 yield input_handle
32 input_handle.close()
33
34
35 with get_file_handle(gbk_filename) as input_handle, open(fa_filename, "w") as output_handle:
36
37 for seq_record in SeqIO.parse(input_handle, "genbank"):
38 if args.remove_version:
39 seq_id = seq_record.id.split('.')[0]
40 else:
41 seq_id = seq_record.id
42 print('Writing FASTA record: {}'.format( seq_id ))
43 output_handle.write(">{}\n{}\n".format(seq_id, seq_record.seq))