python - 如何使用 python 2.4 提取 tar 文件?

标签 python tar

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

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

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

最佳答案

这个例子来自tarfile文档。

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

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

如果你想解压到不同的目录,使用extractall's path parameter :

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

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

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

如果您的 tar 文件中有目录,这可能会失败(我还没有测试过)。有关更完整的解决方案,请参阅 Python 2.7 implementation of extractall

编辑 2:对于使用旧 Python 版本的简单解决方案,请调用 tar command使用 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 - 如何使用 python 2.4 提取 tar 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31163668/

相关文章:

Python:如何创建 tar 文件并使用外部模块动态压缩它,使用 tarfile 模块中不可用的不同压缩方法?

python - 如何正确使用 PyQuery 遍历?

导入 dateutil 的 Python 错误

linux - 文件存档的分布式解压缩

linux - 如何压缩目录但排除文件

c - 简单的 tar 实现?

python - 如何使用python将阿拉伯字符映射到英文字符串

python - mod_mime_magic : can't read `/opt/python/current/app/application.py'

python - if 语句顺序错误,不确定出了什么问题

bash - 不能将 bash 变量用于 tar 的排除