Python boto, list contents of specific dir in bucket

前端 未结 7 1797
难免孤独
难免孤独 2020-12-13 18:19

I have S3 access only to a specific directory in an S3 bucket.

For example, with the s3cmd command if I try to list the whole bucket:

             


        
7条回答
  •  隐瞒了意图╮
    2020-12-13 18:58

    By default, when you do a get_bucket call in boto it tries to validate that you actually have access to that bucket by performing a HEAD request on the bucket URL. In this case, you don't want boto to do that since you don't have access to the bucket itself. So, do this:

    bucket = conn.get_bucket('my-bucket-url', validate=False)
    

    and then you should be able to do something like this to list objects:

    for key in bucket.list(prefix='dir-in-bucket'): 
        
    

    If you still get a 403 Errror, try adding a slash at the end of the prefix.

    for key in bucket.list(prefix='dir-in-bucket/'): 
        
    

    Note: this answer was written about the boto version 2 module, which is obsolete by now. At the moment (2020), boto3 is the standard module for working with AWS. See this question for more info: What is the difference between the AWS boto and boto3

提交回复
热议问题