You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AWS SageMaker Notebook中读取S3存储桶文件夹内的多文件

在SageMaker Notebook中操作S3文件夹文件及权限

一、先确保权限配置正确

SageMaker Notebook实例使用的IAM角色需要具备以下S3权限:

  • s3:ListBucket:用于列出目标桶内的文件
  • s3:GetObject:用于读取文件内容
  • s3:GetObjectAcl:用于获取文件的访问控制列表(权限信息)

如果角色没有这些权限,需要给它附加对应的IAM策略,示例策略如下:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket",
                "s3:GetObject",
                "s3:GetObjectAcl"
            ],
            "Resource": [
                "arn:aws:s3:::your-bucket-name",
                "arn:aws:s3:::your-bucket-name/your-folder-path/*"
            ]
        }
    ]
}

替换your-bucket-name和your-folder-path为实际的桶名和文件夹路径。

二、列出S3文件夹下的所有文件

方法1:使用boto3(AWS官方SDK)

import boto3

# 初始化S3客户端
s3 = boto3.client('s3')

bucket_name = 'your-bucket-name'
folder_prefix = 'your-folder-path/'  # 注意前缀末尾加/,避免匹配到同名前缀的文件

# 列出文件夹下的所有对象
response = s3.list_objects_v2(Bucket=bucket_name, Prefix=folder_prefix)

# 提取文件路径(过滤掉虚拟文件夹)
file_keys = [obj['Key'] for obj in response.get('Contents', []) if not obj['Key'].endswith('/')]

print("文件夹下的文件:")
for key in file_keys:
    print(key)

如果文件数量超过1000个,需要处理分页:

file_keys = []
continuation_token = None

while True:
    if continuation_token:
        response = s3.list_objects_v2(Bucket=bucket_name, Prefix=folder_prefix, ContinuationToken=continuation_token)
    else:
        response = s3.list_objects_v2(Bucket=bucket_name, Prefix=folder_prefix)
    
    # 追加文件路径
    file_keys.extend([obj['Key'] for obj in response.get('Contents', []) if not obj['Key'].endswith('/')])
    
    # 检查是否还有下一页
    if not response.get('IsTruncated'):
        break
    continuation_token = response['NextContinuationToken']

方法2:使用s3fs(文件系统风格操作)

import s3fs

fs = s3fs.S3FileSystem()

bucket_name = 'your-bucket-name'
folder_path = f'{bucket_name}/your-folder-path/'

# 列出文件夹下的所有文件
file_paths = fs.glob(folder_path + '*')

# 过滤掉虚拟文件夹
file_paths = [path for path in file_paths if not fs.isdir(path)]

print("文件夹下的文件:")
for path in file_paths:
    print(path)

三、读取文件内容

读取文本文件(boto3)

for key in file_keys:
    response = s3.get_object(Bucket=bucket_name, Key=key)
    content = response['Body'].read().decode('utf-8')
    print(f"文件 {key} 的内容:")
    print(content[:500])  # 打印前500个字符

读取CSV/Parquet等数据文件(用pandas)

import pandas as pd

# 读取CSV
df = pd.read_csv(f's3://{bucket_name}/{file_keys[0]}')

# 读取Parquet
df = pd.read_parquet(f's3://{bucket_name}/{file_keys[0]}')

四、获取文件的访问权限信息

使用boto3的get_object_acl方法获取文件的ACL权限:

for key in file_keys:
    acl_response = s3.get_object_acl(Bucket=bucket_name, Key=key)
    print(f"\n文件 {key} 的权限信息:")
    for grant in acl_response['Grants']:
        grantee = grant['Grantee']
        permission = grant['Permission']
        # 解析被授权者信息
        if 'DisplayName' in grantee:
            grantee_name = grantee['DisplayName']
        elif 'URI' in grantee:
            grantee_name = grantee['URI']
        else:
            grantee_name = grantee['ID']
        print(f"- 被授权者:{grantee_name},权限:{permission}")

返回的权限通常包括READ、WRITE、READ_ACP、WRITE_ACP、FULL_CONTROL等。


内容的提问来源于stack exchange,提问作者Muhammad Yahya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 09:07:24