使用Boto在S3中读取文件的一部分

时间:2015-05-06 11:55:10

标签: python python-2.7 amazon-s3 cloud boto

我正在尝试读取存储在S3中的700MB文件。我怎么只需要从73到1024位的字节。

我试图找到一个可用的解决方案,但未能成功。如果有人可以帮助我,那将是一个很好的帮助。

3 个答案:

答案 0 :(得分:6)

S3支持GET requests using the 'Range' HTTP header,这就是您所追求的目标。

要在boto中指定范围请求,只需添加一个标题字典,指定'范围'您感兴趣的字节的键。改编自Mitchell Garnaat's response

import boto
s3 = boto.connect_s3()
bucket = s3.lookup('mybucket')
key = bucket.lookup('mykey')
your_bytes = key.get_contents_as_string(headers={'Range' : 'bytes=73-1024'})

答案 1 :(得分:0)

import boto3

obj = boto3.resource('s3').Object('mybucket', 'mykey')
stream = obj.get(Range='bytes=32-64')['Body']
print(stream.read())
来自https://github.com/boto/boto3/issues/1236

boto3版本

答案 2 :(得分:0)

请在此处查看python脚本

import boto3
region = 'us-east-1' # define your region here
bucketname = 'test'  # define bucket
key = 'objkey' # s3 file 
Bytes_range = 'bytes=73-1024'
client = boto3.client('s3',region_name = region)
resp = client.get_object(Bucket=bucketname,Key=key,Range=Bytes_range)
data = resp['Body'].read()