How to list objects by extension from s3 api?

前端 未结 6 816
醉话见心
醉话见心 2021-01-11 16:08

Can i somehow search objects in S3 by extension, not only by prefix?

Here is what i have now:

ListObjectsResponse r = s3Client.ListObjects(new Amazon         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-11 16:27

    I'm iterating after fetching the file information. End result will be in dict

    import boto3
    
    s3 = boto3.resource('s3')
    
    bucket = s3.Bucket('bucket_name')
    
    #get all files information from buket
    files = bucket.objects.all()
    
    # create empty list for final information
    files_information = []
    
    # your known extensions list. we will compare file names with this list
    extensions = ['png', 'jpg', 'txt', 'docx']
    
    # Iterate throgh 'files', convert to dict. and add extension key.
    for file in files:
        if file.key[-3:] in extensions:
            files_information.append({'file_name' : file.key, 'extension' : file.key[-3:]})
        else:
            files_information.append({'file_name' : file.key, 'extension' : 'unknown'})
    
    
    print files_information
    

提交回复
热议问题