如何检查 s3 存储桶中是否存在特定文件

vid*_*hri 4 python csv amazon-s3 amazon-web-services aws-lambda

我是 AWS 新手,我想检查 s3 中的文件夹中是否存在特定的 csv。如果有,我想阅读它,如果没有,我想创建一个 df 并将其上传到 s3。

到目前为止我做了什么

list_of_files = []
    for key in s3_client.list_objects(Bucket= 'abc',Prefix="folder/")['Contents']:
        list_of_files.append(key['Key'])
Run Code Online (Sandbox Code Playgroud)
check_files = [list of file to check]
Run Code Online (Sandbox Code Playgroud)

就像是

if set(check_files) in set(list_of_files):
   read_from_s3(file)
else:
  pd.Dataframe()
Run Code Online (Sandbox Code Playgroud)

小智 6

使用 s3_client get_object。 https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.get_object

如果对象不存在,则会抛出异常 S3.Client.exceptions.NoSuchKey

检查下面的示例

        try:
            s3_client.get_object(
                Bucket=self._bucket,
                Key=key,
            )
            return True
        except s3_client.exceptions.NoSuchKey:
            return False
Run Code Online (Sandbox Code Playgroud)