简体   繁体   English

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

[英]Alternative of “extractall()” of tarfile module in python version 2.4

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

The tarfile module is present in Python 2.4: tarfile模块存在在Python 2.4:

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

Quoting from the module documentation: 引用模块文档:

New in version 2.3. 版本2.3中的新功能。

It is a pure-python module, so it has no C library dependencies that might prevent it from being installed. 它是一个纯python模块,因此它没有可能阻止它安装的C库依赖项。

The TarFile.extractall() function is easily backported: TarFile.extractall()函数很容易被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)

Sorry - a quick check reveals New in version 2.5. 对不起 - 快速检查显示2.5版本中的新功能 against extractall. 反对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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM