使用Python下载,提取和读取gzip文件

Aus*_*son 6 python

我想在Python中下载,提取和迭代文本文件,而不必创建临时文件.

基本上,这个管道,但在python中

curl ftp://ftp.theseed.org/genomes/SEED/SEED.fasta.gz | gunzip | processing step
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

def main():
    import urllib
    import gzip

    # Download SEED database
    print 'Downloading SEED Database'
    handle = urllib.urlopen('ftp://ftp.theseed.org/genomes/SEED/SEED.fasta.gz')


    with open('SEED.fasta.gz', 'wb') as out:
        while True:
            data = handle.read(1024)
            if len(data) == 0: break
            out.write(data)

    # Extract SEED database
    handle = gzip.open('SEED.fasta.gz')
    with open('SEED.fasta', 'w') as out:
        for line in handle:
            out.write(line)

    # Filter SEED database
    pass
Run Code Online (Sandbox Code Playgroud)

我不想使用process.Popen()或任何东西,因为我希望这个脚本与平台无关.

问题是Gzip库只接受文件名作为参数而不是句柄."管道"的原因是下载步骤仅占用了大约5%的CPU,并且同时运行提取和处理会更快.


编辑:这不起作用,因为

"由于gzip压缩的工作方式,GzipFile需要保存其位置并在压缩文件中向前和向后移动.当"文件"是来自远程服务器的字节流时,这不起作用;所有你能做的与它一起检索一个字节,而不是在数据流中来回移动." - 潜入python

这就是我收到错误的原因

AttributeError: addinfourl instance has no attribute 'tell'
Run Code Online (Sandbox Code Playgroud)

那怎么curl url | gunzip | whatever工作?

Ale*_*lli 9

只是gzip.GzipFile(fileobj=handle),你会在你的路上 - 换句话说,"Gzip库只接受文件名作为参数而不是句柄"并不是真的,你只需要使用fileobj=命名参数.

  • Python 2:addinfourl对象(由`urllib.urlopen`创建)不实现需要的`tell`.因此,这个答案在那里不起作用.(在Python 3中,`http.client.HTTPResponse`确实实现了`tell`.) (3认同)