Amazon S3 boto - 如何创建文件夹?

发布于 2024-08-15 07:51:54 字数 132 浏览 6 评论 0原文

如何使用 Amazon s3 的 boto 库在存储桶下创建文件夹?

我按照手册操作,并使用权限、元数据等创建了密钥,但 boto 的文档中没有描述如何在存储桶下创建文件夹,或在存储桶中的文件夹下创建文件夹。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

倾城泪 2024-08-22 07:51:54

S3 中没有文件夹或目录的概念。您可以创建类似 "abc/xys/uvw/123.jpg" 的文件名,许多 S3 访问工具(例如 S3Fox)显示为目录结构,但它实际上只是一个存储桶中的单个文件。

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.

青柠芒果 2024-08-22 07:51:54

假设您想在存储桶中创建文件夹 abc/123/,使用 Boto 小菜一碟

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

或使用 控制台

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

兮颜 2024-08-22 07:51:54

使用这个:

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+'/'))

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+'/'))
大姐,你呐 2024-08-22 07:51:54

使用AWS SDK .Net可以完美工作,只需在文件夹名称字符串末尾添加“/”:

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);

然后刷新您的AWS控制台,您将看到该文件夹

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

澉约 2024-08-22 07:51:54

尝试了上面的许多方法并在键名末尾添加正斜杠 / 来创建目录对我来说不起作用:

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

您必须提供 Body 参数才能创建目录:

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

来源:boto3 问题中的ryantuck

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

山人契 2024-08-22 07:51:54

将“_$folder$”附加到您的文件夹名称并调用 put。

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

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

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/

向日葵 2024-08-22 07:51:54

2019年更新,如果您想创建路径为bucket_name/folder1/folder2的文件夹,可以使用以下代码:

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)

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)
℡寂寞咖啡 2024-08-22 07:51:54

创建文件夹确实很容易。实际上它只是创建密钥。

您可以看到我下面的代码,我正在创建一个以 utc_time 作为名称的文件夹。

请记住以 '/' 结束密钥,如下所示,这表明它是一个密钥:

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

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
蓬勃野心 2024-08-22 07:51:54

尽管您可以通过将“/”附加到文件夹名称来创建文件夹。与常规 NFS 不同,S3 在底层保持扁平结构。

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

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) {});
天涯离梦残月幽梦 2024-08-22 07:51:54

S3没有文件夹结构,但有一种称为键的东西。

我们可以创建 /2013/11/xyz.xls 并将在控制台中显示为文件夹。但S3的存储部分会以此作为文件名。

即使在检索时,我们也发现可以通过使用 ListObjects 方法和使用 Prefix 参数来查看特定文件夹(或键)中的文件。

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.

吃→可爱长大的 2024-08-22 07:51:54

显然您现在可以在 S3 中创建文件夹。我不确定从什么时候开始,但我在“标准”区域中有一个存储桶,可以从“操作”下拉列表中选择“创建文件夹”。

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.

煮茶煮酒煮时光 2024-08-22 07:51:54

这个问题与未来更相关,因此添加此更新。
我正在使用 upload_file 方法,如下所示。

fold ='/my/system/filePath/tabmcq/Tables/auto/18.tsv'
s3_client.upload_file(
            Filename = full/file/path/filename.extension,
            Bucket = "tab-mcq-de",
            Key = f"{fold.split('/')[-3]}/{fold.split('/')[-2]}/{fold.split('/')[-1]}"
    )

想法是“Filename”参数需要你系统的绝对文件路径。
“Key”参数需要文件所在源目录的相对文件路径。

在此示例中,Key 参数必须包含“Tables/auto/18.tsv”值,以便客户端创建文件夹。

希望这有帮助。

This question is more relevant to the future, so adding this update.
I am using the upload_file method as shown below.

fold ='/my/system/filePath/tabmcq/Tables/auto/18.tsv'
s3_client.upload_file(
            Filename = full/file/path/filename.extension,
            Bucket = "tab-mcq-de",
            Key = f"{fold.split('/')[-3]}/{fold.split('/')[-2]}/{fold.split('/')[-1]}"
    )

Ideas is the "Filename" parameter requires the absolute file path of your system.
The "Key" parameter requires the relative file path from the source directory where your files are located

In case of this example, Key parameter has to contain "Tables/auto/18.tsv" value, for client to create the folders.

Hope this helps.

你的呼吸 2024-08-22 07:51:54

以下工作使用Python boto3

s3 = boto3.client("s3")
s3.put_object(Bucket="dest_bucket", Key='folder_name/')

The following works using Python boto3

s3 = boto3.client("s3")
s3.put_object(Bucket="dest_bucket", Key='folder_name/')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文