简体   繁体   中英

NoCredentialError when trying to access head_object

I have the following code which runs as expected:

import boto3

session = boto3.Session(profile_name='default')
s3 = session.resource('s3')
bucketName = 'myBucketName'
bucket = s3.Bucket(bucketName)

for object_summary in bucket.objects.filter(Prefix="MainFolder/"):
    s3_cli = boto3.client('s3')
    if(object_summary.key[-1]!='/'):
        print('FileName: '+object_summary.key)
        # print(s3_cli.head_object(Bucket=bucketName,Key=str(object_summary.key)))
    else:
        s3obj='FolderName: '+object_summary.key
        print(s3obj)

And lists the files and folders present in MainFolder on my S3 bucket. However, when I uncomment Line#12, I get this error:

NoCredentialsError: Unable to locate credentials

Any idea what I am doing wrong?

Instead of:

s3_cli = boto3.client('s3')

you should be using your session which loads the specific profile:

s3_cli = session.client('s3')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM