如何使用Python获取S3存储桶中文件的大小?现有boto3代码输出为空求排查建议
获取S3存储桶文件长度的Python代码问题解决
嘿,我来帮你排查这个问题!你的代码思路是对的,但有个明显的小错误导致输出为空,另外我们也可以补充一些健壮性的处理。
首先解决最直接的打印问题
你当前的print语句里没有占位符,所以.format(file_size)根本没地方插入文件大小的值,自然只会输出前面的文本,看不到file_size。
把print语句改成下面两种方式之一就行:
- 使用
format的占位符:print("Size of the file being processed: {}".format(file_size)) - 更简洁的f-string(Python 3.6+支持):
print(f"Size of the file being processed: {file_size}")
完整的健壮版代码示例
除了打印问题,我们还可以加入对象存在性检查和异常处理,避免因为权限问题或对象不存在导致报错:
import boto3 from botocore.exceptions import ClientError # 替换成你的桶名和对象键 bucket_name = "your-bucket-name" object_key = "path/to/your/file.txt" s3_resource = boto3.resource('s3') try: object_file = s3_resource.Object(bucket_name=bucket_name, key=object_key) # 先加载对象元数据,确认对象存在且有权限访问 object_file.load() file_size = object_file.content_length print(f"Size of the file being processed: {file_size} bytes") except ClientError as e: error_code = e.response['Error']['Code'] if error_code == "404": print(f"Error: 对象 {object_key} 在存储桶 {bucket_name} 中不存在") elif error_code == "403": print(f"Error: 没有访问该存储桶或对象的权限") else: print(f"Unexpected error: {e}")
关键说明
content_length属性本身是正确的,它会返回对象的字节大小,只要对象存在且你有读取该对象元数据的权限就能获取到。- 一定要确保你的boto3已经正确配置了AWS凭证(比如通过环境变量、
~/.aws/credentials文件或者IAM角色,如果是在AWS服务上运行的话),否则会出现权限错误。
内容的提问来源于stack exchange,提问作者padaleswaran jayaperumal
相关产品推荐
相关产品推荐

