Python 如何在S3中从csv提取元素到json 我需要从文件夹中找到csv文件 列出文件夹中的所有文件 将文件转换为json并保存在同一个bucket中
Csv文件,如下图所示,有很多Csv文件Python 如何在S3中从csv提取元素到json 我需要从文件夹中找到csv文件 列出文件夹中的所有文件 将文件转换为json并保存在同一个bucket中,python,amazon-web-services,amazon-s3,aws-lambda,Python,Amazon Web Services,Amazon S3,Aws Lambda,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():
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')
如果删除将保存在文件夹中的bucket name,则无法保存。如何保存回bucket name您可以检查以下代码:
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
你好您能提供输入csv文件/数据的示例吗?@Marcin我给出了任何错误消息?从代码来看,它似乎保存在本地磁盘上,您需要调用一个函数将其上载到s3,类似于
s3。上载文件(f.name、bucket\u name、object\u name)
。仔细检查文件、bucket和对象名称我可以询问fsspec和s3fs。问题是什么use@aysh从s3中读取。Panda可以直接从s3读取数据。应该也能写,但在我现在的测试中,我没有写。最后一个问题是为什么我们需要转换stringI0。抱歉,如果我打扰了您json\u buffer=StringIO()和put(Body=json\u buffer.getvalue()),我没有得到使用line@aysh这是一个解决办法。通常,panda应该能够写入s3。但在我的测试中却没有。也许你会有更多的运气。另一种更传统的写入s3的方法是,在s3.Object(input\u bucket,json\u file)
中使用StringIO.@aysh。您可以将input\u bucket
更改为其他内容。