使用Python boto3检索下载S3存储桶全部PDF及AttributeError报错解决
S3全桶PDF检索下载问题修复方案
错误原因
报错AttributeError: 'str' object has no attribute 'objects'核心问题在于代码错误将存储桶的名称字符串(bucket.name返回值为字符串类型)作为操作对象调用了仅Bucket实例具备的objects属性。
此外原代码使用Prefix='.pdf'的筛选逻辑也不成立:Prefix用于匹配对象键的前缀,PDF属于文件后缀,无法通过前缀规则筛选。
修复后完整实现代码
import boto3 import os # 初始化S3资源,需提前配置好AWS凭证(环境变量、~/.aws/credentials等方式均可) s3 = boto3.resource('s3') # 自定义本地PDF文件存储目录 local_pdf_dir = "./s3_download_pdfs" os.makedirs(local_pdf_dir, exist_ok=True) for bucket in s3.buckets.all(): current_bucket_name = bucket.name print(f"正在扫描存储桶:{current_bucket_name}") # 直接使用Bucket实例调用objects属性 for obj in bucket.objects.all(): # 匹配PDF后缀,加lower()兼容.PDF大写后缀场景,不需要可删除 if obj.key.lower().endswith('.pdf'): pdf_path = f"{current_bucket_name}/{obj.key}" print(f"匹配到PDF文件:{pdf_path}") # 生成本地存储路径,按存储桶名称分目录存储避免重名 local_file_path = os.path.join(local_pdf_dir, current_bucket_name, obj.key) os.makedirs(os.path.dirname(local_file_path), exist_ok=True) # 执行下载 bucket.download_file(obj.key, local_file_path) print(f"下载完成:{local_file_path}")
注意事项
- 运行代码前请确保AWS凭证具备对应存储桶的
s3:ListBucket和s3:GetObject权限 - 如果存储桶内文件数量极大,可使用分页接口优化性能,常规场景上述代码可直接运行
- 如需缩小扫描范围,可将
bucket.objects.all()替换为bucket.objects.filter(Prefix="指定前缀路径/"),仅扫描指定路径下的文件
内容的提问来源于stack exchange,提问作者GuiEpi
相关产品推荐
相关产品推荐

