python版本2.4中tarfile模块的“extractall()”的替代方案

时间:2013-06-28 09:25:08

标签: python compatibility tarfile

来自tarfile模块的

extractall()在Python v2.4中不存在 你能否建议在Python v2.4中提取tarfile的任何替代方法?

2 个答案:

答案 0 :(得分:2)

Python 2.4中的tarfile模块

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

从模块文档中引用:

  

2.3版中的新功能。

它是一个纯python模块,因此它没有可能阻止安装它的C库依赖项。

TarFile.extractall()功能很容易向后移植:

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)

答案 1 :(得分:0)

很抱歉 - 快速检查显示 2.5版中的新功能。反对extractall。

你必须:

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)