我有一个.tar.gz文件,我想解压缩(当我手动解压缩7-Zip时,我在里面得到一个.tar文件)。我可以轻松地解压缩.tar文件然后使用Python tarfile
模块。
当我在Windows资源管理器中右键单击.tar.gz文件时,我可以在文件类型:7-Zip.gz(.gz)下看到。我尝试过使用gzip模块(gzip.open
),但是我得到了一个异常'Not a gzipped file'
。所以应该有其他的方法去。
我在互联网上搜索并看到人们手动使用7-Zip或一些批处理命令,但我找不到在Python中执行此操作的方法。我在Python 2.7上。
答案 0 :(得分:2)
tarfile库能够读取gzipped tar文件。你应该看看这里的例子:
http://docs.python.org/2/library/tarfile.html#examples
第一个例子可能会达到你想要的效果。它将存档的内容提取到当前工作目录:
import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()
答案 1 :(得分:1)
import os
import tarfile
import zipfile
def extract_file(path, to_directory='.'):
if path.endswith('.zip'):
opener, mode = zipfile.ZipFile, 'r'
elif path.endswith('.tar.gz') or path.endswith('.tgz'):
opener, mode = tarfile.open, 'r:gz'
elif path.endswith('.tar.bz2') or path.endswith('.tbz'):
opener, mode = tarfile.open, 'r:bz2'
else:
raise ValueError, "Could not extract `%s` as no appropriate extractor is found" % path
cwd = os.getcwd()
os.chdir(to_directory)
try:
file = opener(path, mode)
try: file.extractall()
finally: file.close()
finally:
os.chdir(cwd)
在此处找到: http://code.activestate.com/recipes/576714-extract-a-compressed-file/
答案 2 :(得分:0)
这是python-docs中的示例,应该可以工作:
import gzip
f = gzip.open('file.txt.gz', 'rb')
file_content = f.read()
f.close()