This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Python program for splitting barcode

Hi All,

I am trying to spit the barcode(which in at beginning of each seq) from a fastq file and save all sequence with similar barcode to new file. I can not figure out whats going wrong in my code.

here is my code so far:

from Bio import SeqIO
barcodes = ['ATGAGATCTT', 'AGCTCATTTC', 'TGAAAATCTT']

for record in SeqIO.parse("sample_sequence.fastq", "fastq"):
    for i in barcodes:
        if record.seq.startswith(i):
            SeqIO.write(record, "first.fastq", "fastq")
#python #fastq

Why not using existed mature tools, try search "barcode split" on this site.

I can not figure out whats going wrong in my code.

You need to explain better what's going wrong. Do you get an error? Is the output not as expected?

I modified your post using the 101010 button to add code markup, making everything easier to read.

1 answer

If you want to filter FASTQ on the prefix of the sequence, you can use awk and regular expressions:

$ awk ' \
    BEGIN { OFS="\n"; }  \
    { \
      a[(NR-1)%4] = $0; \
      if (((NR-1)%4 == 1) && (/^ATGAGATCTT/ || /^AGCTCATTTC/ || /^TGAAAATCTT/)) { \
        b = 1; \
      } \
      if (((NR-1)%4 == 3) && (b == 1)) { \
        print a[0],a[1],a[2],a[3]; \ 
        b = 0; \
      } \
    }' \
    sample_sequence.fastq > first.fastq

Log in to answer this question.