2017-07-11 21 views
0

我想列出S3下子目錄中的文件,但我不能列出文件名以列出S3子目錄中的文件:如何使用Python

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 

能否請你幫我來解決這個問題。

回答

0

您的代碼可以通過在前綴末尾添加/來解決。

使用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對象,這使得一些代碼更簡單。