【问题标题】:How to check give directory or folder exist in given s3 bucket and if exist how to delete the folder from s3?如何检查给定 s3 存储桶中是否存在给定目录或文件夹,如果存在如何从 s3 中删除该文件夹?
【发布时间】:2018-10-31 22:05:30
【问题描述】:

我想检查给 s3 存储桶中是否存在文件夹或目录,如果存在我想使用 python 代码从 s3 存储桶中删除文件夹。

例如:s3:/bucket124/test

这里“bucket124”是存储桶,“test”是文件夹,其中包含一些文件,例如test.txt test1.txt

我想从我的 s3 存储桶中删除文件夹“test”。

【问题讨论】:

  • 你试过什么?哪里失败了?
  • import boto3 from botocore.errorfactory import ClientError from boto.s3.connection import S3Connection, Bucket, Key s3 = boto3.client('s3', aws_access_key_id='AKIA', aws_secret_access_key='vfEn')尝试:bucket = Bucket('AKIA', 'vfEn') s3.head_object(Bucket='bucket124', Key='test') k = boto3.Key(bucket =bucket124, name='test') k.delete( ) 除了 ClientError: print("file not found")
  • 我试过上面的代码
  • 将其编辑到您的问题中。如果您需要实际帮助,请让那些试图帮助您的人过上轻松的生活

标签: python python-3.x amazon-s3 boto boto3


【解决方案1】:

这就是你将如何做到这一点,

import boto3

s3 = boto3.resource('s3')
bucket=s3.Bucket('mausamrest');
obj = s3.Object('mausamrest','test/hello')
counter=0

for key in bucket.objects.filter(Prefix='test/hello/'):
    counter=counter+1

if(counter!=0):
    obj.delete()
print(counter)

ma​​usamrest 是存储桶,test/hello/ 是您要检查项目的目录,但请注意检查后必须删除的一件事 test/hello 而不是 test/hello/ 来删除特定的子文件夹,因此第 5 行的键名是 test/hello

【讨论】:

  • 考虑将objfor-loop 重命名为其他名称以避免混淆。您确定这种方法不会受到here 描述的问题的困扰(即test/hello-this-should-not-have-been-deleted/ 之类的路径也会被删除)?
猜你喜欢
  • 2016-11-12
  • 2022-11-06
  • 2020-06-14
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-05
  • 2018-09-20
相关资源
最近更新 更多