![](/img/trans.png)
[英]copy files from one folder to another on AWS S3 with python
[英]copy files from one AWS s3 bucket/folder to another AWS/S3 folder and also keep the deepest sub-folder name by pythons on databricks
我的問題與上一個將文件從一個 AWS/S3 存儲桶復制到 databricks 上的另一個存儲桶有關。 我創建了一個新線程,因為這個問題與上一個不同。
這篇AWS S3 在兩個存儲桶之間復制文件和文件夾的帖子對我沒有幫助。
我需要通過數據塊上的 python 將一些文件從一個 AWS/S3 存儲桶/文件夾復制到另一個 AWS/S3 存儲桶文件夾。
我的源 S3 存儲桶/文件夾如下:
source_s3_bucket
folder_name1
folder_name2
folder_name3
folder_name4
deepest_folder_name
file1
file2
....
file11500
目標 s3 存儲桶/文件夾:
destination_s3_bucket
dest_folder_name1
dest_folder_name2
dest_folder_name3
deepest_folder_name (this folder name must be exactly same as the source one "deepest_folder_name")
file1
file2
....
file11500
此外,“dest_folder_nameX”都與源文件夾不同,源文件夾和目標文件夾的深度也不同。 但是,源桶中最深的文件夾名稱必須保留在目標桶中。
所有文件必須完全復制並保持相同的名稱。
我試圖做python3編碼:
import boto3
s3 = boto3.client('s3')
s3_resource = boto3.resource('s3')
for key in s3.list_objects(Bucket=source_bucket, Prefix=source_prefix)['Contents']:
files = key['Key']
copy_source = {'Bucket': source_bucket,'Key': files}
s3_resource.meta.client.copy(CopySource=copy_source, Bucket=dest_bucket, Key=dest_prefix)
但是,沒有文件被復制到目標文件夾以及如何保留“deepest_folder_name”?
更新“最深的文件夾”意味着我必須保留該層的子文件夾的名稱並將它們和位於其中的文件復制到目的地。
例如,在源存儲桶中:
folder_name_abc
folder_name_dfr
folder_name_typ # this folder names must be kept
file1
file2
In destination bucket:
folder_name_typ # this folder names must be exactly same as the source
file1
file2
謝謝
棘手的部分是操縱對象鍵的“路徑”部分。
你可以使用這樣的東西:
import boto3
s3_client = boto3.client('s3')
SOURCE_BUCKET = 'bucket1'
SOURCE_PREFIX = 'folder_name_abc/folder_name_dfr/' # Where is Folder located? (Leave blank if root level, include slash at end if Prefix specified)
FOLDER_TO_COPY = 'folder_name_typ'
DESTINATION_BUCKET = 'bucket2'
DESTINATION_PREFIX = '' # (Leave blank if root level, include slash at end if Prefix specified)
# List objects in source directory
bucket_listing = s3_client.list_objects_v2(Bucket=SOURCE_BUCKET,Prefix=f'{SOURCE_PREFIX}{FOLDER_TO_COPY}/')
for object in bucket_listing['Contents']:
print(f'Copying from {object['Key']} to {DESTINATION_PREFIX + object['Key'][len(SOURCE_PREFIX):]}')
s3_client.copy_object(
CopySource = {'Bucket': SOURCE_BUCKET, 'Key': object['Key']},
Bucket = DESTINATION_BUCKET,
Key = DESTINATION_PREFIX + object['Key'][len(SOURCE_PREFIX):] # Remove source prefix, add destination prefix
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.