3
\$\begingroup\$

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'.

seand
2,4651 gold badge20 silver badges29 bronze badges
asked Feb 1, 2012 at 15:32
\$\endgroup\$
2
  • \$\begingroup\$ What's your concern with it now? \$\endgroup\$ Commented Feb 1, 2012 at 15:47
  • \$\begingroup\$ @winston I don't like using the NamedTemporaryFile, and would prefer to use tempfile.TemporaryFile. I don't really have a specific complaint; it just smells a bit funny as it is. \$\endgroup\$ Commented Feb 1, 2012 at 16:21

1 Answer 1

2
\$\begingroup\$

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.

answered Mar 30, 2012 at 13:49
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.