gzip python模块提供空字节

jhdbpxl9  于 2023-01-06  发布在  Python
关注(0)|答案(1)|浏览(92)

我使用Fabric将一个.gz文件复制到远程机器上。当我试图读取同一个远程文件时,显示为空字节。
下面是我用来从远程机器读取zip文件的python代码。

try:
      fabric_connection = Connection(host = host_name, connect_kwargs = {'key_filename' : tmp_id, 'timeout' : 10})
      
      fd = io.BytesIO()
      remote_file = '/home/test/' + 'test.txt.gz'
      fabric_connection.get(remote_file, fd)

      with gzip.GzipFile(mode = 'rb', fileobj = fd) as fin:
         content = fin.read()
         print(content)
         decoded_content = content.decode()
         print(decoded_content)

   except BaseException as err:
      assert not err

   finally:
      fabric_connection.close()

以下为O/P:

b''

我在远程计算机上进行了验证,文件中存在内容。
有人能请让我知道如何解决这个问题。

2mbi3lxu

2mbi3lxu1#

fabric_connect写入fd,文件指针留在文件末尾。在将BytesIO文件传递给GzipFile之前,您需要倒回到文件的前面。

try:
    fabric_connection = Connection(host = host_name, connect_kwargs = {'key_filename' : tmp_id, 'timeout' : 10})
  
    fd = io.BytesIO()
    remote_file = '/home/test/' + 'test.txt.gz'
    fabric_connection.get(remote_file, fd)

    fd.seek(0)

    with gzip.GzipFile(mode = 'rb', fileobj = fd) as fin:
        content = fin.read()
    print(content)
    decoded_content = content.decode()
    print(decoded_content)

except BaseException as err:
    assert not err

finally:
    fabric_connection.close()

相关问题