This is a test version of Biostars. For the public version, visit https://www.biostars.org.
trying to remove empty fasta sequence then creating a new file

I am working in python

from Bio import *
    for current_seq in SeqIO.parse("mysequences.fasta", "fasta"):
        if current_seq.seq.tostring() != '':
            print( ">", current_seq.id, "\n", current_seq.seq.tostring())

I have this so far but there is an error. Also how would I create a file of the cleaned up version?

python fasta

Please clarify if you need assistance with python code or other solutions will work.

Use 101010 button to format code portion of your post properly. I have done it for you this time.

First you want to collect the good records as a list and then write to file. Biopython writing FASTA files is quite well covered in the the documentation here. The first example there under 'Examples: Input/Output Example - Filtering by sequence length' is fairly similar to your needs and so it should be straightforward to adapt.

2 answers

Using bioawk, assuming the file is sequences.fa:

bioawk -c fastx '{ print $name, $seq, length($seq) }' < sequences.fa | awk 'OFS="\n" {if($3>0) print $1, $2}'

Thank you for the help. The files I am using are fasta files. Also, would this command create the edited file?

.fa is a common suffix for fasta, and yes, the output is the cleaned file.

Example:

>chr1
>chr2
TAGCTAGCT

$ bioawk -c fastx '{ print $name, $seq, length($seq) }' < sequences.fa | awk 'OFS="\n" {if($3>0) print ">"$1, $2}'
chr2
TAGCTAGCT
$ bioawk -c fastx '{ print $name, $seq, length($seq) }' < test.fa | awk 'OFS="\n" {if($3>0) print ">"$1, $2}'

Output would be in fasta format.

Ah, forgot the damn >, good catch. Edited.

outstide python:

$ cutadapt -m 1 test.fa
$ awk -v RS='>' '{print ($2!="")?">"$1"\n"$2:""}' test.fa | awk NF
$ seqkit -w 0 seq -gm 1 test.fa

 >chr2
 TAGCTAGCT

For python:

from Bio import SeqIO
with open("new.fa", "w") as o:
    for current_seq in SeqIO.parse("test.fa", "fasta"):
        if len(current_seq.seq) != 0 :
            SeqIO.write(current_seq, o, "fasta")

test.fa is input fasta and new.fa is output fasta. Output fasta will be written in the same directory. If you are familiar with list comprehension in python, following is the way:

from Bio import SeqIO
old_seq=SeqIO.parse("test.fa", "fasta")
new_seq=[seq for seq in old_seq if len(seq.seq) != 0]
SeqIO.write(new_seq, "new.fa", "fasta")

Please read biopython documentation/tutorial. https://biopython.org/wiki/SeqIO. There is an example for filtering sequences by length.

Log in to answer this question.