I'm trying to create a program using python that was will user input a fasta file that can later be used to trim primers. I am trying to use BioPython to do this but I keep running into errors. The code I have tried is as follows:
from Bio import SeqIO
in_file = input("Enter filename with extension:")
def is_fasta(in_file):
with open(in_file) as handle:
fasta = SeqIO.parse(handle, "fasta")
return any(fasta)
is_fasta(in_file)
I want to be able to ask for a fasta file and if the inputted file isn't fasta, show an error message and prompt to try again.
Are you familiar with Python's try
statement? You can just try to open and read the file and if it doesn't work (i. e. raises an exception) you prompt the user again.
I don't know Bio.SeqIO
or even the Bio
module. I guess the error comes with the line containing your call to SeqIO.parse
? You can try something like this:
from Bio import SeqIO
while True:
in_file = input("Enter filename with extension:")
try:
with open(in_file) as handle:
fasta = SeqIO.parse(handle, "fasta")
except:
print("Could not read file. Please ensure it is a 'fasta' file and try again.")
continue
break
Without exception, the assignment of fasta
should have worked and we'll break out of the while
loop with break
.