![](/img/trans.png)
[英]how to copy files and folders from one S3 bucket to another S3 using python boto3
[英]How to combine same files in mutliple folders into one file s3
如果我在 S3 的多个文件夹中有一个文件,如何使用 boto3 python 将它们组合在一起
在桶里说我有
bucket_a
ts
ts_folder
a_date.csv
b_date.csv
c_date.csv
d_date.csv
ts_folder2
a_date.csv
b_date.csv
c_date.csv
d_date.csv
我需要将这两个文件合并为一个文件,同时忽略第二个文件中的 header
我想弄清楚如何使用 boto3 python 或 aws 来实现
尝试这样的事情。 我假设您已在系统上正确设置了 AWS 凭证。 我的建议是首先将 CSV 的行添加到新变量中。 对于第二个 CSV,您将跳过第一行。 找到所有行后,将它们作为字符串连接起来,以便将它们写入 S3 object。
import boto3
# Output will contain the CSV lines
output = []
with open("first.csv", "r") as fh:
output.extend(fh.readlines())
with open("second.csv", "r") as fh:
# Skip header
output.extend(fh.readlines()[1:])
# Combine the lines as string
body = "".join(output)
# Create the S3 client (assuming credentials are setup)
s3_client = boto3.client("s3")
# Write the object
s3_client.put_object(Bucket="my-bucket",
Key="combined.csv",
Body=body)
更新这应该可以帮助您进行 S3 设置
import boto3
session = boto3.session.Session(profile_name='dev')
s3_client = session.client("s3")
bucket = "my-bucket"
files = []
for item in s3_client.list_objects_v2(Bucket=bucket, Prefix="ts/")['Contents']:
if item['Key'].endswith(".csv"):
files.append(item['Key'])
output = []
for file in files:
body = s3_client.get_object(Bucket=bucket,
Key=file)["Body"].read()
output.append(body)
# Combine the lines as string
outputbody = "".join(output)
# Write the object
s3_client.put_object(Bucket=bucket,
Key="combined.csv",
Body=outputbody)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.