I am using a FASTA file with many sequences that I wish to filter. An example of the file is as follows:
>SRR5533383:0::12:0:0:0:
GTGCCAGCAGCCGCGGTAATACGGAGGATCCGAGCGTTATCCGGATTTATTGGGTTTAAAGGGAGCGTAGGCGGACTATTAAGTCAGCTGAGAAAGTTTGCGGCTCAACCGTAAAATTG$
>SRR5533383:0::19:0:0:0:
GTGCCAGCAGCCGCGGTAATACGGAGGATCCGAGCGTTATCCGGATTTATTAGGTTTAAAGGGAGCGTAGATGGATGTTTAAGTCAGTTGTGAAAGTTTGCGGCTCAACCGTAAAATTG$
>SRR5533383:0::17:0:0:0:
GTGCCAGCAGCCGCGGTAATACGGAGGATCCGAGCGTTATCCGGATTTATTGGGTTTAAAGGGAGCGTAGGTGGACATGTAAGTCAGTTGTGAAAGTTTGCGGCTCAACCGTAAAATTG$
Where the line that starts with ">" is the header and the line below it is a sequence. For each sequence there is a header. I want to be able to filter the sequence based on a minimum length (150 base pairs) that they must have in order to be kept in the main file. If the sequence is < 150 then I want it to be removed from the main file and the header of the removed sequence should go to another file ("bad reads file") where the reason it was excluded is included. Such that the output of the "bad reads" file looks like:
>SRR5533383:0::17:0:0:0:
"Excluded because too short"
I'm trying to use the following code to filter the sequences but I can't get it to work:
sequences = {}
with open("seq.fasta") as file:
header = None
data = ''
for line in file:
if line.startswith(">"):
if header and data:
sequences[header] = data
data = ''
header = line.rstrip()
else:
data += line.rstrip()
if header and data:
sequences[header] = data # deal with the last one in the file
for header, data in sequences.items():
print("{}; {}".format(header, data))
#Creates "sequences" in header:sequences
seq = np.asarray(list(data))
print(seq)
#Minimum threshold
min_length = 150
for line in data:
if line >= min_length:
print("Sequences meeting the minimum threshold are kept in paired.fasta")
else:
data.removeline with open("output.log", "w")
print("%i removed because too short" % (header))
python
sequencing