使用Python,你如何纯粹在内存中解压?

时间:2012-01-13 22:58:07

标签: python tar python-requests stringio

我正在一个无法将任何东西保存到磁盘的环境中工作。我需要能够拉出tar文件并解压缩而不保存到磁盘。这似乎失败了:

我试过这个但却抛出了错误:

# fetch.py
from cStringIO import StringIO
import requests
url = "http://example.com/data.tar.gz"
response = requests.get(url)

# ERROR is thrown here. Error shown below
tar = tarfile.open(mode= "r:gz", fileobj = StringIO(response.content))

# This SHOULD break as tar.extract() saves to disk. 
# Can't tell because of error on previous line of code.
data = tar.extract() 

如上面的代码块所述,我在错误行上得到以下回溯:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "./importers/bestbuy_fetcher.py", line 23, in download_bestbuy_batch
    tar = tarfile.open(mode= "r:gz", fileobj = StringIO(response.content))
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/tarfile.py", line 1662, in open
    return func(name, filemode, fileobj, **kwargs)
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/tarfile.py", line 1711, in gzopen
    **kwargs)
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/tarfile.py", line 1689, in taropen
    return cls(name, mode, fileobj, **kwargs)
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/tarfile.py", line 1568, in __init__
    self.firstmember = self.next()
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/tarfile.py", line 2324, in next
    raise ReadError(str(e))
ReadError: invalid header

4 个答案:

答案 0 :(得分:18)

我怀疑该错误告诉您tarfile的文件格式错误。尝试使用wget获取文件并在命令行上解压缩。

关于如何阻止Python将文件内容写入磁盘的另一个问题需要仔细查看tarfile API。而不是调用TarFile.extract()我认为你需要getnames(),它将返回tar文件中每个成员的名称。然后,您可以使用extractfile来获取该成员的内容:

 |  extractfile(self, member)
 |      Extract a member from the archive as a file object. `member' may be
 |      a filename or a TarInfo object. If `member' is a regular file, a
 |      file-like object is returned. If `member' is a link, a file-like
 |      object is constructed from the link's target. If `member' is none of
 |      the above, None is returned.
 |      The file-like object is read-only and provides the following
 |      methods: read(), readline(), readlines(), seek() and tell()

以下是一个例子:

import tarfile    

# Open tarfile
tar = tarfile.open(mode="r:gz", fileobj = file('foo.tgz'))

# Iterate over every member
for member in tar.getnames():
    # Print contents of every file
    print tar.extractfile(member).read()

答案 1 :(得分:11)

原来问题是文件“ data.tar.gz 不是tar存档。只是一个gzip压缩文件。所以我解决了它:

# fetch.py
from cStringIO import StringIO
import gzip
import requests
# Called a 'tar' file but actually a gzip file. @#$%!!!
url = "http://example.com/data.tar.gz"
response = requests.get(url)

results = gzip.GzipFile(fileobj=StringIO(response.content))

感谢所有帮助投球的人!

答案 2 :(得分:8)

您可以尝试我们在处理请求时所做的事情+ tar:使用|模式打开文件。有关详细信息,请参阅http://docs.python.org/library/tarfile.html#tarfile.open

您可以在https://github.com/djeese/djeese-client/blob/master/djeese/commands/clonestatic.py#L53

看到代码

基本上你使用tarfile.open(mode='r|gz', fileobj=response.raw)打开tar文件。

这对我们来说非常有用,并且希望对你也有用。

答案 3 :(得分:2)

这应该有所帮助

import sys
import zipfile
sys.argv[0] = "/home/tom/Documents/REdata/AllListing1RES.zip"
zip_file    = zipfile.ZipFile(sys.argv[0])
items_file  = zip_file.open('AllListing1RES.txt', 'rU')
df = read_table(items_file, sep='\t', index_col=0)