通过SFTP从远程服务器读取GZIP文本文件

时间:2015-11-13 03:09:11

标签: python gzip fabric

我在远程服务器上有许多大文本文件,我想在没有以编程方式解压缩的情况下阅读

我有从远程服务器读取非GZIP文本文件以及在本地读取GZIP文本文件的功能。我不确定如何将两者结合起来或是否可能

以下是单独处理的代码:

from contextlib import closing
from fabric.network import connect
from fabric import state
import gzip

# This successfully reads a non-GZIP text file from user@host:filePath
with closing(connect("user", "host", "port", None)) as ssh:
    with closing(ssh.open_sftp()) as sftp:
        with closing(sftp.open("filePath")) as f:
            for line in f:
                print line

# This successfully reads a GZIP text file locally
with gzip.open("fileName", "r") as f:
    for line in f:
        print line

1 个答案:

答案 0 :(得分:2)

但是,Haven未经测试,您可以将文件处理程序f传递到gzip.GzipFile,如下所示:

with closing(connect("user", "host", "port", None)) as ssh:
    with closing(ssh.open_sftp()) as sftp:
        with closing(sftp.open("filePath")) as f:
            with gzip.GzipFile(mode='rb', fileobj=f) as fin:
                for line in fin:
                    print line
相关问题