我有一个 Amazon S3 存储桶
my-bucket
和文件夹 my-folder
。
我希望我的脚本根据带有
my-folder
的文件是否存在(或不存在)来执行不同的结果。因此,我想检查 my-folder
是否为空并且不包含任何文件。
我该怎么做?
不幸的是,我尝试搜索文档和其他 Stack Overflow 帖子,但似乎找不到类似的内容。
您可以计算前缀中的对象数量:
import boto3
BUCKET_NAME = 'bucket'
FOLDER_NAME = 'my-folder/'
s3_resource = boto3.resource('s3')
bucket = s3_resource.Bucket(BUCKET_NAME)
count = bucket.objects.filter(Prefix=FOLDER_NAME)
print(len(list(count)))
由于@john Rotenstein 代码不适用于嵌套文件夹,所以我编写了这段代码,它的作用就像一个魅力。
def check_files_in_s3_folder(bucket_name, folder_name):
"""
Checks if there is any file in a specified folder within an S3 bucket.
Parameters:
- bucket_name: The name of the S3 bucket.
- folder_name: The name of the folder inside the bucket.
Returns:
- True if the folder contains files, False otherwise.
"""
# Ensure the folder name ends with a slash
if not folder_name.endswith('/'):
folder_name += '/'
# Initialize a session using Amazon S3
s3 = boto3.client('s3')
try:
# List objects within the specified folder
response = s3.list_objects_v2(Bucket=bucket_name, Prefix=folder_name, Delimiter='/')
# Check if the folder actually contains files directly
if 'Contents' in response:
# Ensure there's at least one object directly in the folder
for obj in response['Contents']:
if obj['Key'] != folder_name: # Exclude the folder itself if listed
return True
return False
except Exception as e:
print(f"An error occurred: {e}")
return False