我正在尝试使用python 2.4.2完全提取.tar文件,因此并非tarfile模块的所有方面都可用。我查看了python纪录片,但我发现它没有帮助,因为我继续犯语法错误。以下是我尝试过的命令(没有成功):
tarfile.Tarfile.getnames(tarfile.tar)
tarfile.Tarfile.extract(tarfile.tar)
有一种简单的方法可以完全提取我的焦油吗?如果是这样,使用的格式是什么?另外,我想要注意tarfile.TarFile.extractall()在我的python版本中不可用。
答案 0 :(得分:23)
此示例来自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/')
编辑:我现在看到你使用的是旧的Python版本,它没有TarFile.extractall()
方法。 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)
答案 1 :(得分:3)
这是torchvision library中更通用的代码:
import os
import hashlib
import gzip
import tarfile
import zipfile
def _is_tarxz(filename):
return filename.endswith(".tar.xz")
def _is_tar(filename):
return filename.endswith(".tar")
def _is_targz(filename):
return filename.endswith(".tar.gz")
def _is_tgz(filename):
return filename.endswith(".tgz")
def _is_gzip(filename):
return filename.endswith(".gz") and not filename.endswith(".tar.gz")
def _is_zip(filename):
return filename.endswith(".zip")
def extract_archive(from_path, to_path=None, remove_finished=False):
if to_path is None:
to_path = os.path.dirname(from_path)
if _is_tar(from_path):
with tarfile.open(from_path, 'r') as tar:
tar.extractall(path=to_path)
elif _is_targz(from_path) or _is_tgz(from_path):
with tarfile.open(from_path, 'r:gz') as tar:
tar.extractall(path=to_path)
elif _is_tarxz(from_path):
with tarfile.open(from_path, 'r:xz') as tar:
tar.extractall(path=to_path)
elif _is_gzip(from_path):
to_path = os.path.join(to_path, os.path.splitext(os.path.basename(from_path))[0])
with open(to_path, "wb") as out_f, gzip.GzipFile(from_path) as zip_f:
out_f.write(zip_f.read())
elif _is_zip(from_path):
with zipfile.ZipFile(from_path, 'r') as z:
z.extractall(to_path)
else:
raise ValueError("Extraction of {} not supported".format(from_path))
if remove_finished:
os.remove(from_path)