简体   繁体   English

从子文件夹 Boto3 中获取所有文件

[英]Get all File from Subfolder Boto3

I have this code to download all the files from a buckets AWS S3我有这段代码可以从存储桶 AWS S3 下载所有文件

import os
import boto3

#initiate s3 resource
s3 = boto3.resource('s3')

s3 = boto3.resource(
    's3',
    aws_access_key_id = '__________',
    aws_secret_access_key = '________',
    region_name = '______'
)


# select bucket
my_bucket = s3.Bucket('MainBucket')

# download file into current directory
for s3_object in my_bucket.objects.all():
    # Need to split s3_object.key into path and file name, else it will give error file not found.
    path, filename = os.path.split(s3_object.key)
    my_bucket.download_file(s3_object.key, filename)

Inside that bucket, I have a folder called "pictures"在那个桶里,我有一个名为“图片”的文件夹

How can I get the files only in my folder?我怎样才能只在我的文件夹中获取文件?

My try:我的尝试:

s3.Bucket('MainBucket/pictures')

Inside that bucket, I have a folder called "pictures"在那个桶里,我有一个名为“图片”的文件夹

How can I get the files only in my folder?我怎样才能只在我的文件夹中获取文件?

You can get the files only in the "pictures" folder by providing a prefix:您只能通过提供前缀来获取“图片”文件夹中的文件:

# select bucket
my_bucket = s3.Bucket('MainBucket')

# download file into current directory
for s3_object in my_bucket.objects.filter(Prefix='pictures/'): <-- FILTER 'PICTURES'
    # Need to split s3_object.key into path and file name, else it will give error file not found.
    path, filename = os.path.split(s3_object.key)
    my_bucket.download_file(s3_object.key, filename)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM