【问题标题】:How to list the files in S3 subdirectory using Python如何使用 Python 列出 S3 子目录中的文件
【发布时间】:2023-03-13 22:05:01
【问题描述】:

我正在尝试列出 S3 中子目录下的文件,但我无法列出文件名:

import boto
from boto.s3.connection import S3Connection
access=''
secret=''
conn=S3Connection(access,secret)
bucket1=conn.get_bucket('bucket-name')
prefix='sub -directory -path'
print bucket1.list(prefix) 
files_list=bucket1.list(prefix,delimiter='/') 
print files_list
for files in files_list:
  print files.name

你能帮我解决这个问题吗?

【问题讨论】:

    标签: python amazon-web-services amazon-s3 boto


    【解决方案1】:

    您的代码可以通过在前缀末尾添加/ 来修复。

    使用boto3 的现代等价物是:

    import boto3
    s3 = boto3.resource('s3')
    
    ## Bucket to use
    bucket = s3.Bucket('my-bucket')
    
    ## List objects within a given prefix
    for obj in bucket.objects.filter(Delimiter='/', Prefix='fruit/'):
        print(obj.key)
    

    输出:

    fruit/apple.txt
    fruit/banana.txt
    

    这段代码没有使用S3客户端,而是使用了boto3提供的S3对象,这使得一些代码更简单。

    【讨论】:

    • 这种方法上市有限制吗?此方法是否会列出我的存储桶中有 5000 或 7000 个对象的所有键。
    • @ShivkumarMallesappa 请创建一个新问题,而不是通过对旧问题的评论提出问题。
    • @ShivkumarMallesappa 在 boto3 中使用资源旨在让您避免在较低级别使用 API 时所需的分页编码。
    【解决方案2】:

    您可以使用 boto3 来做到这一点。 列出所有文件。

    import boto3
    s3 = boto3.resource('s3')
    bucket = s3.Bucket('bucket-name')
    objs = list(bucket.objects.filter(Prefix='sub -directory -path'))
    for i in range(0, len(objs)):
        print(objs[i].key)
    

    这段代码将打印子目录中存在路径的所有文件

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      • 2014-10-16
      • 1970-01-01
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      • 2011-12-23
      相关资源
      最近更新 更多