【问题标题】:Read h5 file using AWS boto3使用 AWS boto3 读取 h5 文件
【发布时间】:2022-04-29 03:30:39
【问题描述】:

我正在尝试使用 boto3 从 AWS S3 读取 h5 文件。

client = boto3.client('s3',key ='key')
result = client.get_object(Bucket='bucket', Key='file')
with h5py.File(result['Body'], 'r') as f:
    data = f

TypeError:预期的 str、bytes 或 os.PathLike 对象,而不是 StreamingBody

有什么想法吗?

h5py版本是2.10,boto3版本是1.7.58

同样的问题是here,但没有答案...

【问题讨论】:

    标签: python amazon-web-services amazon-s3 boto3 h5py


    【解决方案1】:

    h5py.File() 命令需要磁盘上本地文件的路径。但是,您正在将内存中的数据传递给它。

    您可以通过以下方式下载文件

    import boto3
    
    s3_client = boto3.client('s3')
    
    s3_client.download_file('bucket', 'key', 'filename')
    
    with h5py.File('filename', 'r') as f:
        data = f
    

    【讨论】:

      【解决方案2】:

      使用临时文件进行临时存储的有效解决方案。 这会将模型数据从您的 s3 存储桶流式传输到临时存储并将其设置为变量。

      import tempfile
      from keras import models
      import boto3
      
      # Creating the low level functional client
      client = boto3.client(
          's3',
          aws_access_key_id = 'ACCESS_KEY_ID',
          aws_secret_access_key = 'ACCESS_SECRET_KEY',
          region_name = 'us-east-1'
      )
      
      
      # Create the S3 object
      response_data = client.get_object(
          Bucket = 'bucket-name',
          Key = 'model/model.h5'
      )
      
      model_name='model.h5'
      response_data=response_data['Body']
      response_data=response_data.read()
      #save byte file to temp storage
      with tempfile.TemporaryDirectory() as tempdir:
          with open(f"{tempdir}/{model_name}", 'wb') as my_data_file:
              my_data_file.write(response_data)
              #load byte file from temp storage into variable
              gotten_model=models.load_model(f"{tempdir}/{model_name}")
      print(gotten_model.summary())
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-02
        • 2017-07-23
        • 2021-10-18
        • 2021-10-12
        • 1970-01-01
        • 2012-03-04
        • 2016-04-15
        • 2017-04-21
        相关资源
        最近更新 更多