【问题标题】:Google Cloud Storage gcsfs - read a .tar file directly into pythonGoogle Cloud Storage gcsfs - 将 .tar 文件直接读入 python
【发布时间】:2021-04-06 10:38:35
【问题描述】:

我在 GCS 中有一个 .tar 文件,我希望能够将文件直接读入 python,而无需先在某处下载文件的中间步骤。

我在想这样的事情:

import gcsfs
fs = gcsfs.GCSFileSystem(project='my-google-project')

with fs.open('my_bucket/my_tar_file.tar', 'rb') as f:
    tarfile.open(f)

但是f 是一个已经打开的文件连接,所以.open 当然再次不起作用。这可能吗?

【问题讨论】:

    标签: python google-cloud-platform google-cloud-storage tar


    【解决方案1】:

    我像 @LaurentLAPORTE 一样使用 tarfile 库,但以不同的方式实现它。使用 fs 对象打开 tar 文件,然后使用 tarfile.open 的文件对象并循环访问 tarfile 成员以获取文件的内容。

    import tarfile
    import gcsfs
    
    fs = gcsfs.GCSFileSystem(project="your-project-here")
    
    with fs.open('your-bucket/test.tar') as f:
        tr = tarfile.open(fileobj=f, mode='r:')
    
        for member in tr.getmembers():
            f=tr.extractfile(member)
            content=f.read()
            print(content.decode('utf-8')) // add decode since output in bytes and not in utf-8 format
        tr.close()
    

    test.tar(也上传到我的存储桶)包含 sample_file.txt,其内容是:

    试运行:

    【讨论】:

      【解决方案2】:

      tarfile.open 函数接受 fileobj 参数:

      如果指定了fileobj,它将用作以二进制模式打开的文件对象的替代名称。它应该在位置 0。

      所以,这个解决方案应该可行:

      import contextlib
      import tarfile
      
      import gcsfs
      
      
      fs = gcsfs.GCSFileSystem(project="my-google-project")
      
      with contextlib.closing(tarfile.open(fileobj=fs, mode='r:')) as f:
          for entry in f:
              ...
      

      不要忘记关闭您的 fs 文件。

      【讨论】:

      • 嗯看起来有一些问题...mode=r: 失败并显示ValueError: mode must be 'r', 'a', 'w' or 'x'。更改为其他模式会得到AttributeError: 'GCSFileSystem' object has no attribute 'tell'。最后,不确定您是否想到了整个目录或特定文件 - 但只是为了确认我希望能够打开特定文件,而不是 target_dir中的每个文件@
      • 嗯,我的第一个答案是tarfile.open,参数与tarfile.TarFile不同。我回复我的答案……
      • 您可以使用TarFile.getmember(name) 来获取特定名称的TarInfo 对象。
      • 你测试过这个吗?我不认为它会起作用:(我有同样的AttributeError
      猜你喜欢
      • 2018-06-25
      • 1970-01-01
      • 2020-05-05
      • 2018-11-27
      • 1970-01-01
      • 2015-04-09
      • 2021-07-27
      • 2019-11-17
      • 2023-03-05
      相关资源
      最近更新 更多