This is a test version of Biostars. For the public version, visit https://www.biostars.org.
[Python] reads from fastq file

I am looking for the fastest python code to extract only reads from fastq file and store it in new file.

python fastq

to extract only reads from fastq file and store it in new file

What do you want to do?

as a beginner of python, i just need to learn how to do it.

You just want to copy all reads to a new file?

yes i want to copy all reads to a new file

Do you mean fastq to fasta?

Well, you better be a more precise next time when asking questions.

4 answers

from Bio import SeqIO

SeqIO.convert('myfile.fastq','fastq','myoutput.fasta','fasta')
$ python -c "import subprocess; subprocess.check_call(\"awk '{ if (NR%4==1) { print \\\">\\\"\$0; } else if (NR%4==2) { print \$0; } }' source.fq > destination.fa\", shell=True)"

Or:

#!/usr/bin/env python
import subprocess
subprocess.check_call("awk '{ if (NR%4==1) { print \">\"$0; } else if (NR%4==2) { print $0; } }' source.fq > destination.fa", shell=True)

While technically correct and probably the most efficient, it doesn't really teach OP something about Python :-p

Doing things on the command line is going to be the fastest route, so the subprocess library is useful to know, if the asker is forced to use Python.

this is a general code snippet to copy files, what you are asking for... but quite useless in my opinion.

with open("myfile.fastq") as infile, open("myoutput.fastq", 'w') as output:
    for line in infile:
        output.write(line)

I guess @thebioinfo wants only reads, so each 4the line.

As you are looking for fastq to fasta, I think t is a duplicated question here

If you want to learn some python you may try:

import sys
filename = sys.argv[1]

with open(filename, "r") as infile:
    line_ct = 0
    for line in infile:
        if (line_ct % 4 == 0):
            print(">" + line[1:], end="")
            line_ct = 0
        if (line_ct  == 1):
            print(line, end = "")
        line_ct += 1

Log in to answer this question.