0

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

4

2 回答 2

2

tarfile模块存在于 Python 2.4 中:

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)
于 2013-06-28T09:39:19.293 回答
0

抱歉 - 快速检查显示2.5 版中的新功能。反对提取物。

你不得不:

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)
于 2013-06-28T09:46:24.697 回答