How to extract tar file using python 2.4?

I am trying to fully extract a .tar file using python 2.4.2 and due to this, not all aspects of the tarfile module can be used. I looked through the python doc and I didn't find it useful as I keep making syntax errors. Below are the commands I have tried (without any success):

tarfile.Tarfile.getnames(tarfile.tar)
tarfile.Tarfile.extract(tarfile.tar)

      

Is there an easy way to completely extract my tar? If so, what formatting is used? Also, I would like to point out that tarfile.TarFile.extractall () is not available in my python version.

+3


source to share


1 answer


This example is from the tarfile

docs.

import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()

      

First, the TarFile object is created with tarfile.open()

, then all files are extracted with, extractall()

and finally the object is closed.

If you want to extract to a different directory use the option : extractall

path

tar.extractall(path='/home/connor/')

      



Edit: Now I see that you are using an older version of Python (<2.5? Can you be more specific?) Which has no method TarFile.extractall()

. The documentation for older tarfile versions confirms this. Instead, you can do something like this:

for member in tar.getmembers():
    print "Extracting %s" % member.name
    tar.extract(member, path='/home/connor/')

      

If your tar file has directories in it, it probably won't work (I haven't tested it). For a more complete solution see Python 2.7 Implementationextractall

Edit 2: For a simple solution using an older version of Python, invoke the tar command usingsubprocess.call

import subprocess
tarfile = '/path/to/myfile.tar'
path = '/home/connor'
retcode = subprocess.call(['tar', '-xvf', tarfile, '-C', path])
if retcode == 0:
    print "Extracted successfully"
else:
    raise IOError('tar exited with code %d' % retcode)

      

+10


source







All Articles