【问题标题】:How to extract the elements from csv to json in S3如何在 S3 中将元素从 csv 提取到 json
【发布时间】:2020-11-30 16:59:39
【问题描述】:
  • 我需要从文件夹中找到 csv 文件
  • 列出文件夹内的所有文件
  • 将文件转换为json并保存在同一个桶中

csv文件,像下面这么多csv文件

emp_id,Name,Company
10,Aka,TCS
11,VeI,TCS

代码如下

import boto3
import pandas as pd
def lambda_handler(event, context):
    s3 = boto3.resource('s3')
    my_bucket = s3.Bucket('testfolder')
    for file in my_bucket.objects.all():
        print(file.key)
    for csv_f in file.key:
        with open(f'{csv_f.replace(".csv", ".json")}', "w") as f:
            pd.read_csv(csv_f).to_json(f, orient='index')

如果您删除存储桶名称将无法保存,它将保存在文件夹中。如何保存回存储桶名称

【问题讨论】:

  • 嗨。您能提供输入 csv 文件/数据的示例吗?
  • @Marcin 我给了
  • 任何错误信息?
  • 从代码看来是保存在本地磁盘上,需要调用函数上传到s3,类似于s3.upload_file(f.name, bucket_name, object_name)
  • boto3.amazonaws.com/v1/documentation/api/latest/guide/… 仔细检查文件、存储桶和对象名称

标签: python amazon-web-services amazon-s3 aws-lambda


【解决方案1】:

您可以查看以下代码:

from io import StringIO

import boto3
import pandas as pd

s3 = boto3.resource('s3')

def lambda_handler(event, context):
    
    s3 = boto3.resource('s3')
    
    input_bucket = 'bucket-with-csv-file-44244'
    
    my_bucket = s3.Bucket(input_bucket)
    
    for file in my_bucket.objects.all():
        
        if file.key.endswith(".csv"):
           
            csv_f = f"s3://{input_bucket}/{file.key}"
            
            print(csv_f)
            
            json_file = file.key.replace(".csv", ".json")
            
            print(json_file)
            
            json_buffer = StringIO()
            
            df = pd.read_csv(csv_f)
            
            df.to_json(json_buffer, orient='index')
            
            s3.Object(input_bucket, json_file).put(Body=json_buffer.getvalue())            

您的 lambda 层需要:

fsspec
pandas
s3fs

【讨论】:

  • 我能问一下 fsspec 和 s3fs。有什么用
  • @aysh 从 s3 读取。 Panda 可以直接从 s3 读取。应该也能写,但是我现在的测试,我没有写。
  • 最后一个问题,为什么我们需要转换 stringI0。对不起,如果我打扰你了 json_buffer = StringIO() 和 put(Body=json_buffer.getvalue()) 我没有得到使用线路的信息
  • @aysh 这是一种解决方法。通常 panda 应该能够写入 s3。但在我的测试中没有。也许你会有更多的运气。另一种更传统的写入 s3 的方式是 here,它涉及 StringIO。
  • @aysh in s3.Object(input_bucket, json_file) 你可以把 input_bucket 改成别的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-08
  • 1970-01-01
相关资源
最近更新 更多