Python boto, list contents of specific dir in bucket

前端 未结 7 1790
难免孤独
难免孤独 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 19:08

    The following code will list all the files in specific dir of the S3 bucket:

    import boto3
    
    s3 = boto3.client('s3')
    
    def get_all_s3_keys(s3_path):
        """
        Get a list of all keys in an S3 bucket.
    
        :param s3_path: Path of S3 dir.
        """
        keys = []
    
        if not s3_path.startswith('s3://'):
            s3_path = 's3://' + s3_path
    
        bucket = s3_path.split('//')[1].split('/')[0]
        prefix = '/'.join(s3_path.split('//')[1].split('/')[1:])
    
        kwargs = {'Bucket': bucket, 'Prefix': prefix}
        while True:
            resp = s3.list_objects_v2(**kwargs)
            for obj in resp['Contents']:
                keys.append(obj['Key'])
    
            try:
                kwargs['ContinuationToken'] = resp['NextContinuationToken']
            except KeyError:
                break
    
        return keys
    

提交回复
热议问题