HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Using temporary file as backing object for a tarfile

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filetemporarybackingusingfortarfileobject

Problem

I have existing code that handles a tarball and would like to use that to process a directory, so I thought it would be reasonable to pack the directory up in a temporary file. I ended up writing:

class temp_tarball( object ):
    def __init__( self, path ):
        self.tmp = tempfile.NamedTemporaryFile()
        self.tarfile = tarfile.open( None, 'w:', self.tmp )
        self.tarfile.add( path, '.' )
        self.tarfile.close()
        self.tmp.flush()
        self.tarfile = tarfile.open( self.tmp.name, 'r:' )
    def __del__( self ):
        self.tarfile.close()
        self.tmp.close()


I am looking for a cleaner way to reopen the tarfile with mode 'r'.

Solution

You could try:

def __init__(self, path):
    self.tmp = tempfile.TemporaryFile()
    self.tarfile = tarfile.open( fileobj=self.tmp, mode='w:' )
    self.tarfile.add( path, '.' )
    self.tarfile.close()
    self.tmp.flush()
    self.tmp.seek(0)
    self.tarfile = tarfile.open( fileobj=self.tmp, mode='r:' )


tarfile() will take a fileobj in the constructor instead of a name, so as long as you don't close it, and instead just seek() to 0 when you want to re-read it, you should be good.

Code Snippets

def __init__(self, path):
    self.tmp = tempfile.TemporaryFile()
    self.tarfile = tarfile.open( fileobj=self.tmp, mode='w:' )
    self.tarfile.add( path, '.' )
    self.tarfile.close()
    self.tmp.flush()
    self.tmp.seek(0)
    self.tarfile = tarfile.open( fileobj=self.tmp, mode='r:' )

Context

StackExchange Code Review Q#8557, answer score: 2

Revisions (0)

No revisions yet.