[英]Moving file based on filename with Amazon S3
需要根據名稱將 Amazon S3 文件移動到名稱相同的相應文件夾中。 這適用於 AWS 上 python 中的自動化腳本。 文件名遞增 1。
例如,一個將被稱為my_file_section_a
,然后下一個將是my_file_section_b1
,然后下一個將是my_file_section_b2
等等。 這些文件夾將被稱為my_file_section_a
、 my_file_section_b1
等等。
這是代碼:
from __future__import print_function
import boto3
import time, urllib
import json
print("*"*80)
print("Initializing...")
print("*"*80)
s3 = boto3.client('s3')
def lambda_handler(event, context):
source_bucket = event['Records'[0]['s3']['bucket']['name']
object_key = event['Records'][0]['s3']['object']['key']
target_bucket = 'myfilelambdadestination'
copy_source = {'Bucket': source_bucket, 'Key': object_key}
print("Source bucket: ", source_bucket)
print("Target bucket: ", target_bucket)
print("Log Stream name: ",context.log_stream_name)
print("Log Group name: ",context.log_group_name)
print("Request ID: ",context.aws_request_id)
print("Mem. limits(MB) ", context.memory_limit_in_mb)
try:
print("Using waiter to waiting for object to persist through s3 service")
waiter = s3.get_waiter('object_exists')
waiter.wait(Bucket=source_bucket, Key = object_key)
s3.copy_object(Bucket=target_bucket, Key = object_key, CopySource = copy_source)
return response['ContentType']
except Exception as err:
print("Error -" +str(err))
return e
如何將基於名稱的文件移動到名稱相同的文件夾中?
新文件夾是不帶擴展名的文件名。 根據 object_key 的外觀,您可能已經調整了此代碼
object_key = 'my_file_section_b2.txt'
new_object_prefix = object_key.rsplit('/', 1)[-1].split('.')[0]
new_object_key = new_object_prefix + '/' + object_key
new_object_key
'my_file_section_b2/my_file_section_b2.txt'
這里是一個AWS Lambda function,它將一個object復制到一個同名目錄,然后刪除原來的ZA8CFDE6331BD54B6F666C。
它只會從bucket的根目錄復制對象,避免復制的object再次觸發Lambda function,造成死循環。 (Amazon S3 很大,但不是無限的)如果您的目標是不同的存儲桶。 這將沒有必要。
import boto3
import urllib
def lambda_handler(event, context):
# Get the bucket and object key from the Event
bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'])
# Only copy objects that were uploaded to the bucket root (to avoid an infinite loop)
if '/' not in key:
# Copy object
s3_client = boto3.client('s3')
s3_client.copy_object(
Bucket = bucket,
Key = f"{key}/{key}",
CopySource= {'Bucket': bucket, 'Key': key}
)
# Delete source object
s3_client.delete_object(
Bucket = bucket,
Key = key
)
function 需要一個 IAM 角色,該角色具有對存儲桶的GetObject
和PutObject
(可能更多?)權限。 創建此 AWS Lambda function 后,在 Amazon S3 存儲桶上創建一個事件以在創建 ZA8CFDE63311C4BEB66 時觸發 function。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.