【发布时间】:2019-07-09 18:43:00
【问题描述】:
所以,我想从 S3 存储桶中读取一个大的 CSV 文件,但我不希望该文件完全下载到内存中,我想做的是以某种方式将文件分块流式传输,然后进行处理。
到目前为止,这就是我所做的,但我认为这不能解决问题。
import logging
import boto3
import codecs
import os
import csv
LOGGER = logging.getLogger()
LOGGER.setLevel(logging.INFO)
s3 = boto3.client('s3')
def lambda_handler(event, context):
# retrieve bucket name and file_key from the S3 event
bucket_name = event['Records'][0]['s3']['bucket']['name']
file_key = event['Records'][0]['s3']['object']['key']
chunk, chunksize = [], 1000
if file_key.endswith('.csv'):
LOGGER.info('Reading {} from {}'.format(file_key, bucket_name))
# get the object
obj = s3.get_object(Bucket=bucket_name, Key=file_key)
file_object = obj['Body']
count = 0
for i, line in enumerate(file_object):
count += 1
if (i % chunksize == 0 and i > 0):
process_chunk(chunk)
del chunk[:]
chunk.append(line)
def process_chunk(chuck):
print(len(chuck))
【问题讨论】:
-
使用botocore.amazonaws.com/v1/documentation/api/latest/reference/…iter_chunks() 或iter_lines()
-
旁注:只要对象小于500MB,您可以将其下载到
/tmp,然后像普通本地文件一样处理它。
标签: amazon-s3 python-3.6