Black_Hat
Black_Hat

Reputation: 981

Alternative of "extractall()" of tarfile module in python version 2.4

extractall() from the tarfile module in not present in Python v2.4 Can you suggest any alternate approach to extract a tarfile in Python v2.4?

Upvotes: 0

Views: 2008

Answers (2)

Steve Barnes
Steve Barnes

Reputation: 28415

Sorry - a quick check reveals New in version 2.5. against extractall.

You will have to:

import tarfile

tf = tarfile.TarFile("YourTarFile.tar")
members = tf.getmembers()
for member in members:
    where_to_put_it = "*somthing based on the member path probably!*"
    print 'Extracting', member
    tf.extract(member, where_to_put_it)

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1125118

The tarfile module is present in Python 2.4:

http://docs.python.org/release/2.4/lib/module-tarfile.html

Quoting from the module documentation:

New in version 2.3.

It is a pure-python module, so it has no C library dependencies that might prevent it from being installed.

The TarFile.extractall() function is easily backported:

import copy
import operator
import os.path
from tarfile import ExtractError

def extractall(tfile, path=".", members=None):
    directories = []

    if members is None:
        members = tfile

    for tarinfo in members:
        if tarinfo.isdir():
            # Extract directories with a safe mode.
            directories.append(tarinfo)
            tarinfo = copy.copy(tarinfo)
            tarinfo.mode = 0700
        tfile.extract(tarinfo, path)

    # Reverse sort directories.
    directories.sort(key=operator.attrgetter('name'))
    directories.reverse()

    # Set correct owner, mtime and filemode on directories.
    for tarinfo in directories:
        dirpath = os.path.join(path, tarinfo.name)
        try:
            tfile.chown(tarinfo, dirpath)
            tfile.utime(tarinfo, dirpath)
            tfile.chmod(tarinfo, dirpath)
        except ExtractError, e:
            if tfile.errorlevel > 1:
                raise
            else:
                tfile._dbg(1, "tarfile: %s" % e)

Upvotes: 2

Related Questions