Boto3 delete object inside directory

16,005

The keyname in S3 contains also the directory path, there are no real directories in buckets.
Do it like this:

s3 = session.resource("s3")
obj = s3.Object("mybucket", "media/private/test.txt")
obj.delete()
Share:
16,005
Marco Herrarte
Author by

Marco Herrarte

DevOps, CloudOps, IT passionate

Updated on June 23, 2022

Comments

  • Marco Herrarte
    Marco Herrarte almost 2 years

    I have the following snippet:

    import boto3
    
    session = boto3.Session(
        aws_access_key_id="id",
        aws_secret_access_key="secret",
        region_name="us-east-1"
    )
    
    s3 = session.resource("s3")
    obj = s3.Object("mybucket", "test.txt")
    
    
    obj.delete()
    

    It works fine if the file is on the root of the bucket, but I need to delete a file inside a directory. My file is under: mybucket/media/private/test.txt

    Adding the path to "mybucket" or "test.txt" in the s3.Object() is not working

  • Michael - sqlbot
    Michael - sqlbot almost 6 years
    There shouldn't be a leading slash in the object key. I think boto3 quietly removes it for you, so this may work as written, but it isn't precisely correct.
  • Abilash Amarasekaran
    Abilash Amarasekaran over 5 years
    Hi I wanted to ask how to use this if we only know partial file name. ie I know only test as the file name instead of test-1xxxxx222.txt. How could I use this to delete it?
  • Zach Rieck
    Zach Rieck almost 4 years
    @AbilashAmarasekaran Use the startswith method (i.e. if file.startswith('test') : file.delete() ) (programiz.com/python-programming/methods/string/startswith)