Necessary to close pysam.AlignmentFile?
1
0
Entering edit mode
4.7 years ago
AlchemistMoz ▴ 20

Hi, This question is for those who are familiar with pysam.

pysam is used as follows:

samfile = pysam.AlignmentFile('file.bam', 'rb')

In the examples shown in the documentation, he always ends the code with:

samfile.close()

Similar to when closing a file in python.

I can't find anything about the exact purpose of this in the documentation for pysam. Is it similar to when closing a regular file?

I'm asking because I wan't to create a function where samfile is returned to the caller function. Would I then need to close the samfile in the caller function?

eg.:

def open_bam(file):
    samfile = pysam.AlignmentFile(file, 'rb')
    return samfile
    samfile.close()

And then use it as follows:

def analyze_bam(sfile):
    for read in sfile.fetch():
        print read

    sfile.close()

Or can I simply skip closing it in analyze_bam()?

python pysam BAM • 1.5k views
ADD COMMENT
2
Entering edit mode
4.7 years ago

If you open a file in a function and want to return it, then you can't close it. In your open_bam() example, remove the last line, which will never be reached.

Anyway, yes, closing samfile is the same as closing a regular file. In theory python will do it for you when the process finishes, but I've seen cases where this doesn't happen (mostly with images in matplotlib).

ADD COMMENT
0
Entering edit mode

Okay, so if I remove samfile.close() from open_bam() and keep return samfile, could I then do something like this?:

bam_graph(open_bam('filename.bam'))

def bam_graph(samfile):
    Code to produce graph and then end it with:
    samfile.close()

Will it be okay then to structure my script like this or is it possible that this will invoke problems further down the road?

ADD REPLY
0
Entering edit mode

That'd be fine.

ADD REPLY

Login before adding your answer.

Traffic: 2766 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6