此示例来自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 版本的简单解决方案,请使用 subprocess.call 调用 tar command
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)