使用boto3将csv文件保存到s3

ncecgwcz  于 2023-06-19  发布在  其他
关注(0)|答案(4)|浏览(157)

我正在尝试写入CSV文件并将其保存到s3中的特定文件夹(exist)。这是我的代码:

from io import BytesIO
import pandas as pd
import boto3
s3 = boto3.resource('s3')

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)

csv_buffer = BytesIO()

bucket = 'bucketName/folder/'
filename = "test3.csv"
df.to_csv(csv_buffer)
content = csv_buffer.getvalue()

def to_s3(bucket,filename,content):
  s3.Object(bucket,filename).put(Body=content)

to_s3(bucket,filename,content)

这是我得到的错误:

Invalid bucket name "bucketName/folder/": Bucket name must match the regex "^[a-zA-Z0-9.\-_]{1,255}$"

我也试过:

bucket = bucketName/folder

以及:

bucket = bucketName
key = folder/
s3.Object(bucket,key,filename).put(Body=content)

有什么建议吗?

o3imoua4

o3imoua41#

保存到s3存储桶中也可以使用upload_file和现有的. csv文件完成:

import boto3
s3 = boto3.resource('s3')

bucket = 'bucket_name'
filename = 'file_name.csv'
s3.meta.client.upload_file(Filename = filename, Bucket= bucket, Key = filename)
mw3dktmi

mw3dktmi2#

这个应该能用

def to_s3(bucket,filename, content):
    client = boto3.client('s3')
    k = "folder/subfolder"+filename
    client.put_object(Bucket=bucket, Key=k, Body=content)
vvppvyoh

vvppvyoh3#

这应该可以工作:

bucket = bucketName
key = f"{folder}/{filename}"
csv_buffer=StringIO()
df.to_csv(csv_buffer)
content = csv_buffer.getvalue()
s3.put_object(Bucket=bucket, Body=content,Key=key)

AWS存储桶名称不允许包含斜杠(“/”),斜杠应是Key的一部分。AWS使用斜线在 Jmeter 板中显示“虚拟”文件夹。因为csv是一个文本文件,所以我使用StringIO而不是BytesIO

xqk2d5yq

xqk2d5yq4#

这对我很有效

import os
import pandas as pd
import boto3
from io import StringIO

from dotenv import load_dotenv
load_dotenv("/path/to/.env", override=True)

def df_to_s3(df, bucket, key):
    # Create a session
    session = boto3.session.Session(profile_name=os.environ.get("AWS_SECRETS_PROFILE_NAME"))
    aws_s3_client = session.client(
        service_name="s3",
        region_name=os.environ.get("AWS_SECRETS_REGION_NAME"),
    )

    # Create a CSV string from the DataFrame
    csv_buffer = StringIO()
    df.to_csv(csv_buffer, index=False)

    # Put the CSV string to S3
    aws_s3_client.put_object(
        Body=csv_buffer.getvalue(),
        Bucket=bucket,
        Key=key
    )
    print(f'Successfully put DataFrame to {bucket}/{key}')
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df_to_s3(df, 'bucketName/folder/', 'test3.csv')

相关问题