Skip to content
Wang Yunfei edited this page Feb 9, 2017 · 1 revision

mFile

mFile is an extended file class. It is used to open file from various sources, such as stdin, stdout, stderr, stringFile object and gzipped files.

from ngslib import mFile

Read from stdin

from ngslib import mFile
with mFile('stdin') as ifh:
    for line in ifh:
        print line.rstrip()

Save this code as testmFile.py, then run:

echo "This is an example input." | python testmFile.py

Output:

This is an example input.

Write into stdout or stderr

from ngslib import mFile
with mFile('stdout') as ofh:
    print >> ofh, "This is test output."
with mFile('stderr') as ofh:
    print >> ofh, "This is test error output." 

Save this file into testmFileOutput.py, then run:

python testmFileOutput.py  >output.txt 2> erroroutput.txt 

Content of output.txt:

This is test output.

Content of erroroutput.txt:

This is test error output.

Manipulating gzipped file

with mFile("test.txt.gz") as ifh:
    for line in ifh:
        print line.rstrip()
with mFile('test2.txt.gz','w') as ofh:
    print >> ofh, "This is a test gzipped output."

Note: gzipped input from stdin or output to stdout/stderr are currently not supported. Use alternative methods like this:

Gzipped input from stdin:

 gunzip -c test.txt.gz | python testgzip.py

Gzipped output into stdout:

 python testgzip.py |gzip >test2.txt.gz

Manipulating stringFile object

from ngslib import mFile,stringFile
mstr='''>act-1
ACGATCGTGCATTACGTCGATCGTAGCATGCTAGCTGCGTACGTAGCTTGCTA
>egl-1
CAGTCTAGCATCGTACGATCGTGCTACGTACGTATCGTACGATCGTACGTAGCT'''
with mFile(stringFile(mstr)) as ifh:
    with mFile(stringFile()) as ofh:
        for line in ifh:
            print >>ofh, line.rstrip()
        # get the string out from stringFile
        print str(ofh).rstrip()

Output:

>act-1
ACGATCGTGCATTACGTCGATCGTAGCATGCTAGCTGCGTACGTAGCTTGCTA
>egl-1
CAGTCTAGCATCGTACGATCGTGCTACGTACGTATCGTACGATCGTACGTAGCT

Clone this wiki locally