我有一个.tar.gz文件,我想解压(当我用7-Zip手动解压缩时,我在里面得到一个.tar文件)。我可以轻松地解压缩这个.tar文件,然后使用Python模块。
当我在中右键单击.tar.gz文件时,我可以看到文件类型: 7-Zip.gz (.gz)。我尝试过使用gzip模块(gzip.open),但是我得到了一个异常'Not a gzipped file'。所以应该还有别的路要走。
我在互联网上搜索过,看到人们手动使用7-Zip或一些批处理命令,但是我无法找到在Python中这样做的方法。我正在使用Python 2.7。
发布于 2014-03-04 13:08:45
tarfile库能够读取gzipped tar文件。您应该看看这里的示例:
http://docs.python.org/2/library/tarfile.html#examples
第一个例子可能实现您想要的结果。它将存档的内容提取到当前工作目录:
import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()发布于 2014-03-04 13:04:45
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/
发布于 2014-03-04 13:03:18
这是python中的示例,应该可以工作:
import gzip
f = gzip.open('file.txt.gz', 'rb')
file_content = f.read()
f.close()https://stackoverflow.com/questions/22172605
复制相似问题