I have a script that searches through a csv file and a fasta file and any ID's that are in both files will be used to extract the fasta sequence from fasta file. It looks like this:
import os
import shlex
import subprocess
import argparse
import glob
import pysam
from pysam import FastaFile
#setup options for this program
parser = argparse.ArgumentParser()
group = parser.add_argument_group('Options for annotation.py')
group.add_argument(
'-f', '--fasta', help='FASTA file (RAST). all_fprau.fasta', required=True)
group.add_argument(
'-c', '--csv', help='CSV file (parsed orthomcl groups). parsed_groups.csv',
required=True)
args = parser.parse_args()
fasta = FastaFile(args.fasta)
with open(args.csv) as infile:
infile.readline() ## skip header
for index, line in enumerate(infile):
strain, matches = line.strip().split("\t")
if not len(matches):
print('Warning: Skipping strain {}. No matches'.format(strain))
continue
matches = set(matches.split(',')) # remove duplicates
key = '{}.faa'.format(strain)
with open(key, 'w') as out_file:
for match in matches:
name = 'fig|{}'.format(match)
try:
sequence = fasta[name]
except KeyError:
print('Sequence absent in FASTA file {0}: {1}'.format(args.fasta, name))
continue
out_file.write(">{0}\n{1}\n".format(name, sequence))
I am having a problem running this script however. I get this error:
File "pysam/libcfaidx.pyx", line 123, in pysam.libcfaidx.FastaFile.__cinit__
File "pysam/libcfaidx.pyx", line 183, in pysam.libcfaidx.FastaFile._open
OSError: error when opening file `all_fprau.fasta`
The fasta file all_fprau.fasta
contains a large number of sequences and I think that this may be the problem? When I cut down the size of the file the script works, however I need all the sequences to be available for the next step in this pipeline to work. I have tried to use:
fasta = glob.glob("/home/brian/my_orthomcl_dir/annotations/*.fasta")
in place of
fasta = FastaFile(args.fasta)
in an attempt to search through the fasta files individually, but i get the error: TypeError: list indices must be integers or slices, not str
, in relation to line 38 in the script above:
sequence = fasta[name]
Any help or suggestions would be very much appreciated!