【问题标题】:python - s3 Boto3 read N number of lines per iteration from large filepython - s3 Boto3 从大文件中每次迭代读取 N 行
【发布时间】:2021-03-11 14:57:22
【问题描述】:

我正在尝试使用 python 在 N 行中处理来自 s3 的大文件的所有记录。我每次迭代都必须获取 N 行。每行都有一些 json 对象。

以下是我已经尝试过的一些事情:

1) 我尝试了这里提到的解决方案 Streaming in / chunking csv's from S3 to Python 但它在读取数据字节时破坏了我的 json 结构。

2)

obj = s3.get_object(Bucket=bucket_name, Key=fname)
data=obj['Body'].read().decode('utf-8').splitlines()

读取 100k 行的大文件需要更多时间。它将返回行列表,我们可以进一步迭代以从数据变量中获取行数。

【问题讨论】:

    标签: python amazon-s3 boto3


    【解决方案1】:

    smart_open 可能会成功。

    pip install smart_open[s3] 
    

    安装后...

    from smart_open import open
    
    client = boto3.client("s3")
    transport_params = {'client': client}
    with open('s3://%s/%s' % (bucket_name, fname), 'wb', transport_params=transport_params, encoding='utf-8') as f:
        for line in f:
            print(json.loads(line))
    

    你也可以使用iter_lines

    obj = s3.get_object(Bucket=bucket_name, Key=fname)
    for line in obj['Body'].iter_lines(chunk_size=1024, keepends=False):
        print(json.loads(line))
    

    【讨论】:

    • 嗨..这会给我一行,块大小以字节为单位。显示它不会按要求返回 N 行。
    【解决方案2】:

    那些正在寻找类似解决方案的人。我已经利用 pandas 库来获得 N 个循环中的行数。

    下面是我的代码实现,每次迭代将给出 50 行

    for records in pd.read_json(obj['Body'].read().decode('utf-8'), lines=True, chunksize=50):
        print(records)
    

    【讨论】:

      猜你喜欢
      • 2017-04-21
      • 1970-01-01
      • 2018-05-13
      • 2011-08-03
      • 2021-05-22
      • 2017-09-29
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      相关资源
      最近更新 更多