Entering edit mode
7.6 years ago
chrisgbeldam
▴
20
Hi All
I've written some BioPython but I want to be able to generate an error message if the protein searched for is not in my fasta file? I've use try and except but there must be a better way to do it than that?
for myuniprot in myuniprots:
try:
for record in SeqIO.parse("uniprot_sprot.fasta", "fasta"):
protein_id = record.id.split('|')[1] if '|' in record.id else record.id
protein_name = record.id.split('|')[2] if '|' in record.id else record.id
if protein_id == myuniprot:
protein_sequence = (record.seq)
seq = 1
for n in range(len(protein_sequence)-15):
current = str((protein_sequence[n:n+16]))
seqfilename = myuniprot + "_" + str(seq)
textfilename = seqfilename + ".txt"
seq += 1
if not os.path.exists(myuniprot):
os.makedirs(myuniprot)
b = open(myuniprot+ "/" + textfilename, 'w')
b.write(current)
b.close()
except:
print("my uniprot was not found")
Never use except without specifying which error you are catching (e.g. KeyError). You use try-except if you expect a specific error in rare cases.
So which line throws the exception? Can't you write an if statement for that?
I don't see how this is bioinformatics - this is purely programming.
I'm asking here because it's in relation to BioPython and fasta files which are Bioinformatics
This is a programming question - it concerns loops and conditions. I'm not convinced it qualifies as bioinformatics just because it involves BioPython. I'd redirect you to SO but that place is hell.
My $0.02 - create a dict of IDs and check against that. Or you know, use bioawk if you're not particular about BioPython.
Why not just print your own error message to STDERR?
Something to the effect of:
Argh, nasty synthax!
or
Copied off an old SO post ;)