如何使用 Python 列出 S3 子目录中的文件

pra*_*mar 6 python amazon-s3 boto amazon-web-services

我正在尝试列出 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
Run Code Online (Sandbox Code Playgroud)

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

Joh*_*ein 10

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

使用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)
Run Code Online (Sandbox Code Playgroud)

输出:

fruit/apple.txt
fruit/banana.txt
Run Code Online (Sandbox Code Playgroud)

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

  • 这种方法对上市有什么限制吗?此方法将列出我的存储桶中有 5000 或 7000 个对象的所有键。 (2认同)

Ash*_*uGG 8

您可以使用 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)
Run Code Online (Sandbox Code Playgroud)

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