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

2024-04-18 13:11:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在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

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


Tags: 文件nameimportsecretprefixs3bucketaccess
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)

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

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

使用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对象,这使得一些代码更简单。

相关问题 更多 >