ChatGPT解决这个技术问题 Extra ChatGPT

Amazon S3 boto - how to create a folder?

How can I create a folder under a bucket using boto library for Amazon s3?

I followed the manual, and created the keys with permission, metadata etc, but no where in the boto's documentation it describes how to create folders under a bucket, or create a folder under folders in bucket.

it seems amazon s3 doesn't have concept of folder, some suggest creating key with name like "folder/test.txt' to get around it. i tried using firefox s3 plugin to create folder, and list all keys in boto, it outputs the folder i just created as "], so how can i view/add/modify content to/from this folder?
Note: the AWS S3 management interface option for creating "folders" is not compatible with S3FS i.e. create a "folder" using the interface and try to get a listing of said folder through S3FS mount point.
Note2: creating a "folder" through S3FS is compatible with AWS S3 Management interface though.
See @JaHax answer below for an example of how to do this with Boto. Easy!

R
Rahul K P

There is no concept of folders or directories in S3. You can create file names like "abc/xys/uvw/123.jpg", which many S3 access tools like S3Fox show like a directory structure, but it's actually just a single file in a bucket.


thanks for the answer, so i guess if i want to see the contents of a particular folder, i will need to traverse lots other unnecessary files?
there is very well defined concept of folders. the answer is incorrect.. see elranu answer below.
@BoppityBop: There is no concept of folders in S3. S3 does not have folders, even though the management console and many tools do represent keys with slashes as such. See Working with Folders and read the part: "So the console uses object key names to present folders and hierarchy. In Amazon S3, you have only buckets and objects."
It might not technically be a folder, but there definitely seems to be folder support. In the aws console when looking at a bucket you can click "Create Folder" and it will make one, and they can be empty, and pull meta data from them.
S3 is a giant, custom DynamoDB key-value store. Some tools (including the AWS web console) provide some functionality that mimics a directory tree, but you'll be working against S3 rather than working with it if your applications assume it's equivalent to a file system. Renaming what appears to be a directory, for instance, requires scanning through the keyspace and modifying every key containing the 'directory name' in question. On the other hand, being a key-value store, there's no need for creating 'parent directories' or cleaning 'empty folders', which mimicking a file system would require
T
TomNg

Assume you wanna create folder abc/123/ in your bucket, it's a piece of cake with Boto

k = bucket.new_key('abc/123/')
k.set_contents_from_string('')

Or use the console


This is the correct answer. It is possible with Boto and this is how you do it. Actually the new_key() is all you need. The string sent to the function could be abc/123/ or abc/123/newfile.txt. Whatever you prefer. I like to wrap this in an if statement after I try to get what I hope is there like this: key = bucket.get_key(upgrade_path) if key is None: key = bucket.new_key(upgrade_path) Essentially, if it is not there, create it!
With the latest api, bucket.key('abc/123/') will also achieve the same result.
Specifying a directory key also works with uploading files in multipart uploads mp = self._bucket.initiate_multipart_upload(bucket_key)
I would guess this is outdated by now or the question should include some instructions about what bucket is. This method new_key doesn't seem to be available in any S3-related class in boto3 anymore.
R
Reza Amya

Use this:

import boto3
s3 = boto3.client('s3')
bucket_name = "YOUR-BUCKET-NAME"
directory_name = "DIRECTORY/THAT/YOU/WANT/TO/CREATE" #it's name of your folders
s3.put_object(Bucket=bucket_name, Key=(directory_name+'/'))

Thanks for the help, I am getting below error. can you please help me .botocore.exceptions.NoCredentialsError: Unable to locate credentials
You need to specify your aws credentials in some way or the other. Check this out : boto3.readthedocs.io/en/latest/guide/…
e
elranu

With AWS SDK .Net works perfectly, just add "/" at the end of the folder name string:

var folderKey =  folderName + "/"; //end the folder name with "/"
AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(AWSAccessKey, AWSSecretKey);
var request = new PutObjectRequest();
request.WithBucketName(AWSBucket);
request.WithKey(folderKey);
request.WithContentBody(string.Empty);
S3Response response = client.PutObject(request);

Then refresh your AWS console, and you will see the folder


Just tried this with the AWS::S3 ruby library. It creates a "folder" with a file with a blank filename in it... So it doesn't really work. Mohammad Asgari's solution works fine though!
@Nico but did you end the filename with a "/", just as the code comment says?
Yes, I added the slash. I did AWS::S3::S3Object.store('test/', '', 'my_bucket')
Issued "putObject" using empty string and slash on the end worked for me. I'm using PHP with the tpyo/amazon-s3-php-class library.
@BoppityBop yes it has a create folder button, but that probably just makes some sort of empty file as well
M
Mamad Asgari

Append "_$folder$" to your folder name and call put.

    String extension = "_$folder$";
    s3.putObject("MyBucket", "MyFolder"+ extension, new ByteArrayInputStream(new byte[0]), null);

see: http://www.snowgiraffe.com/tech/147/creating-folders-programmatically-with-amazon-s3s-api-putting-babies-in-buckets/


This way of creating a folder is no longer working. You should try the way suggested by @TomNg
a
azzamsa

Tried many method above and adding forward slash / to the end of key name, to create directory didn't work for me:

client.put_object(Bucket="foo-bucket", Key="test-folder/")

You have to supply Body parameter in order to create directory:

client.put_object(Bucket='foo-bucket',Body='', Key='test-folder/')

Source: ryantuck in boto3 issue


G
Gabriel Wu

It's really easy to create folders. Actually it's just creating keys.

You can see my below code i was creating a folder with utc_time as name.

Do remember ends the key with '/' like below, this indicates it's a key:

Key='folder1/' + utc_time + '/'

client = boto3.client('s3')
utc_timestamp = time.time()


def lambda_handler(event, context):

    UTC_FORMAT = '%Y%m%d'
    utc_time = datetime.datetime.utcfromtimestamp(utc_timestamp)
    utc_time = utc_time.strftime(UTC_FORMAT)
    print 'start to create folder for => ' + utc_time

    putResponse = client.put_object(Bucket='mybucketName',
                                    Key='folder1/' + utc_time + '/')

    print putResponse

I
Ilya Vinnichenko

Update for 2019, if you want to create a folder with path bucket_name/folder1/folder2 you can use this code:

from boto3 import client, resource

class S3Helper:

  def __init__(self):
      self.client = client("s3")
      self.s3 = resource('s3')

  def create_folder(self, path):
      path_arr = path.rstrip("/").split("/")
      if len(path_arr) == 1:
          return self.client.create_bucket(Bucket=path_arr[0])
      parent = path_arr[0]
      bucket = self.s3.Bucket(parent)
      status = bucket.put_object(Key="/".join(path_arr[1:]) + "/")
      return status

s3 = S3Helper()
s3.create_folder("bucket_name/folder1/folder2)

v
vpage

Although you can create a folder by appending "/" to your folder_name. Under the hood, S3 maintains flat structure unlike your regular NFS.

var params = {
            Bucket : bucketName,
            Key : folderName + "/"
        };
s3.putObject(params, function (err, data) {});

C
CDub

S3 doesn't have a folder structure, But there is something called as keys.

We can create /2013/11/xyz.xls and will be shown as folder's in the console. But the storage part of S3 will take that as the file name.

Even when retrieving we observe that we can see files in particular folder (or keys) by using the ListObjects method and using the Prefix parameter.


P
Perelx

Apparently you can now create folders in S3. I'm not sure since when, but I have a bucket in "Standard" zone and can choose Create Folder from Action dropdown.