A folder on S3 [^ 1] using the boto3 library, which is an API wrapper for Python to AWS. Or I wrote a function to check if the file exists.
There was a process that I wanted to distinguish by the presence or absence of a folder on S3, but on the net it is a process that uses boto2 and a function that is not currently implemented, or it can only be used for "files" on S3 There were only a few methods, and there was almost no existence judgment for "folders".
So I made it myself.
import boto3
from botocore.exceptions import ClientError
client = boto3.client('s3')
bucket_name = 'hoge'
key = "fuga/piyo/bar/" # /I think it's a good idea to put up to. It may not be necessary. I'm not sure.
result = client.list_objects(Bucket=bucket_name, Prefix=key)
#Next is Kimo. If the above path does not exist, some of the returned results will be
#There is no key called Contents. Existence can be determined by using this.
if "Contents" in result:
exists = True
else:
exists = False
[^ 1]: Strictly not a folder. On S3, everything is managed by a combination of keys (like paths) and values (contents of files), like a dictionary in Python. In S3, the key happens to be represented by a / delimiter like a path, and in the browser, the AWS viewer just interprets it nicely with a / delimiter.
Recommended Posts