我开发了一个类似于@Kirk Broadhurst 的代码,但是如果每个块的处理时间超过 5 分钟(大约),就会发生连接超时。以下代码通过为每个块打开一个新连接来工作。
import boto3
import pandas as pd
import numpy as np
# The following credentials should not be hard coded, it's best to get these from cli.
region_name = 'region'
aws_access_key_id = 'aws_access_key_id'
aws_secret_access_key = 'aws_secret_access_key'
s3 =boto3.client('s3',region_name=region_name,aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key)
obj = s3.get_object(Bucket='bucket', Key='key')
total_bytes = obj['ContentLength']
chunk_bytes = 1024*1024*5 # 5 MB as an example.
floor = int(total_bytes//chunk_bytes)
whole = total_bytes/chunk_bytes
total_chunks = [1+floor if floor<whole else floor][0]
chunk_size_list = [(i*chunk_bytes, (i+1)*chunk_bytes-1) for i in range(total_chunks)]
a,b = chunk_size_list[-1]
b = total_bytes
chunk_size_list[-1] = (a,b)
chunk_size_list = [f'bytes={a}-{b}' for a,b in chunk_size_list]
prev_str = ''
for i,chunk in enumerate(chunk_size_list):
s3 = boto3.client('s3', region_name=region_name, aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key)
byte_obj = s3.get_object(Bucket='bucket', Key='key', Range=chunk_size_list[i])
byte_obj = byte_obj['Body'].read()
str_obj = byte_obj.decode('utf-8')
del byte_obj
list_obj = str_obj.split('\n')
# You can use another delimiter instead of ',' below.
if len(prev_str.split(',')) < len(list_obj[1].split(',')) or len(list_obj[0].split(',')) < len(list_obj[1].split(',')):
list_obj[0] = prev_str+list_obj[0]
else:
list_obj = [prev_str]+list_obj
prev_str = list_obj[-1]
del str_obj, list_obj[-1]
list_of_elements = [st.split(',') for st in list_obj]
del list_obj
df = pd.DataFrame(list_of_elements)
del list_of_elements
gc.collect()
# You can process your pandas dataframe here, but you need to cast it to correct datatypes.
# casting na values to numpy nan type.
na_values = ['', '#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN', '-NaN', '-nan', '1.#IND', '1.#QNAN', 'N/A', 'NA', 'NULL', 'NaN', 'n/a', 'nan', 'null']
df = df.replace(na_values, np.nan)
dtypes = {col1: 'float32', col2:'category'}
df = df.astype(dtype=dtypes, copy=False)