简体   繁体   English

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

[英]Amazon S3 boto - how to create a folder?

How can I create a folder under a bucket using boto library for Amazon s3?如何使用 Amazon s3 的boto库在存储桶下创建文件夹?

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.我遵循了手册,并创建了具有权限、元数据等的密钥,但在 boto 的文档中没有描述如何在存储桶下创建文件夹,或在存储桶中的文件夹下创建文件夹。

There is no concept of folders or directories in S3. 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. 您可以创建文件名,例如"abc/xys/uvw/123.jpg" ,许多S3访问工具(例如S3Fox显示为目录结构,但实际上只是存储桶中的单个文件。

Assume you wanna create folder abc/123/ in your bucket, it's a piece of cake with Boto 假设您想在存储桶中创建文件夹abc / 123 /,这与Boto无关紧要

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

Or use the console 或使用控制台

With AWS SDK .Net works perfectly, just add "/" at the end of the folder name string: 使用AWS开发工具包.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);

Then refresh your AWS console, and you will see the folder 然后刷新您的AWS控制台,您将看到该文件夹

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

Append "_$folder$" to your folder name and call put. 将“ _ $ folder $”添加到您的文件夹名称并放回电话。

    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/ 参见: http : //www.snowgiraffe.com/tech/147/creating-folders-programmatically-with-amazon-s3s-api-putting-babies-in-buckets/

Update for 2019, if you want to create a folder with path bucket_name/folder1/folder2 you can use this code: 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)

S3 doesn't have a folder structure, But there is something called as keys. S3没有文件夹结构,但是有一些称为键的东西。

We can create /2013/11/xyz.xls and will be shown as folder's in the console. 我们可以创建/2013/11/xyz.xls并在控制台中将其显示为文件夹。 But the storage part of S3 will take that as the file name. 但是S3的存储部分会将其作为文件名。

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. 即使在检索时,我们也会发现通过使用ListObjects方法和Prefix参数可以看到特定文件夹(或键)中的文件。

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. 您可以看到以下代码,我正在创建一个以utc_time为名称的文件夹。

Do remember ends the key with '/' like below, this indicates it's a key: 请记住,如下所示以'/'结尾该键,这表明它是键:

Key='folder1/' + utc_time + '/' 键='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

Although you can create a folder by appending "/" to your folder_name. 尽管您可以通过在文件夹名后添加“ /”来创建文件夹。 Under the hood, S3 maintains flat structure unlike your regular NFS. 在幕后,S3与常规的NFS不同,保持平坦的结构。

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

Apparently you can now create folders in S3. 显然,您现在可以在S3中创建文件夹。 I'm not sure since when, but I have a bucket in "Standard" zone and can choose Create Folder from Action dropdown. 我不确定从什么时候开始,但是我在“标准”区域中有一个存储桶,可以从“操作”下拉菜单中选择“创建文件夹”。

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: 您必须提供Body参数才能创建目录:

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

Source: ryantuck in boto3 issue 资料来源: ryantuck在boto3期中

This question is more relevant to the future, so adding this update.这个问题与未来更相关,因此添加此更新。 I am using the upload_file method as shown below.我正在使用 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]}"
    )

Ideas is the "Filename" parameter requires the absolute file path of your system.思路是“Filename”参数需要你系统的绝对文件路径。 The "Key" parameter requires the relative file path from the source directory where your files are located “Key”参数需要文件所在源目录的相对文件路径

In case of this example, Key parameter has to contain "Tables/auto/18.tsv" value, for client to create the folders.在此示例中,Key 参数必须包含“Tables/auto/18.tsv”值,以便客户端创建文件夹。

Hope this helps.希望这可以帮助。

The following works using Python boto3以下作品使用 Python boto3

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM