Here is how I was able to export to a standard gzipped FASTQ file using Biopython. Basically, instead of using SeqIO.write
, I directly called the .format
method of the SeqRecord object. The example code below imports a gzipped FASTQ file, removes reads that do not contain a G in positions 7, 8, and 9, and writes the results to a gzipped FASTQ file.
from Bio import SeqIO
import gzip
path_in = "path/to/in.fastq.gz"
path_out = "path/to/out.fastq.gz"
handle_in = gzip.open(path_in, "rt")
handle_out = gzip.open(path_out, "wt")
fq = SeqIO.parse(handle_in, "fastq")
for read in fq:
# Only export reads that have a G in positions 7, 8,
# and 9
if read.seq[6:9] == "GGG":
handle_out.write(read.format("fastq"))
handle_in.close()
handle_out.close()
Using the code example from the original question that converts a FASTA file to a FASTQ file, it would look something like the following:
fastq = gzip.open("path/to/out.fastq.gz", "wt")
for record in SeqIO.parse(fasta, "fasta"):
fastq.write(record.format("fastq"))
fastq.close()
Caveat: This only works for Python 3. Python 3 differs from Python 2 in how it imports data from binary files (source). In fact, ideally you should be using Python 3.4 or greater since Biopython has compatibility issues with Python 3.3 (source).