如何使用 python 2.4 提取 tar 文件? [英] How do I extract a tar file using python 2.4?

查看:26
本文介绍了如何使用 python 2.4 提取 tar 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 python 2.4.2 完全提取 .tar 文件,因此并非 tarfile 模块的所有方面都可用.我浏览了 python 纪录片,但我没有发现它对我有帮助,因为我继续犯语法错误.以下是我尝试过的命令(没有成功):

I'm trying to extract a .tar file completely using python 2.4.2 and because of this not all of the aspects of the tarfile module are usable. I've looked through the python documentary and I have not found it to be helpful as I continue to make syntax errors. The following are commands I have tried(to no success):

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

有没有一种简单的方法可以完全提取我的焦油?如果是这样,使用的格式是什么?另外,我想指出 tarfile.TarFile.extractall() 在我的 python 版本中不可用.

Is there a simple way to extract my tar completely? If so what is the formatting used? Also, I'd like to note that tarfile.TarFile.extractall() is not available in my python version.

推荐答案

这个例子来自 tarfile 文档.

This example is from the tarfile docs.

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

首先,使用 tarfile.open() 创建一个 TarFile 对象,然后使用 extractall() 提取所有文件,最后关闭该对象.

First, a TarFile object is created using tarfile.open(), then all files are extracted using extractall() and finally the object is closed.

如果你想解压到不同的目录,使用extractallpath 参数:

If you want to extract to a different directory, use extractall's path parameter:

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

我现在看到您使用的是没有 TarFile.extractall() 方法的旧 Python 版本.旧版本 tarfile 的文档证实了这一点.您可以改为执行以下操作:

I see now that you are using an old Python version which doesn't have the TarFile.extractall() method. The documentation for older versions of tarfile confirms this. You can instead do something like this:

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

如果您的 tar 文件中有目录,这可能会失败(我还没有测试过).有关更完整的解决方案,请参阅 Python 2.7 实现全部提取

If your tar file has directories in it, this probably fails (I haven't tested it). For a more complete solution, see the Python 2.7 implementation of extractall

编辑 2:对于使用旧 Python 版本的简单解决方案,请调用 tar 命令 使用 subprocess.call

Edit 2: For a simple solution using your old Python version, call the tar command using subprocess.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)

这篇关于如何使用 python 2.4 提取 tar 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆