【问题标题】:not able to create folders in aws s3 using boto3无法使用 boto3 在 aws s3 中创建文件夹
【发布时间】:2021-04-23 03:30:20
【问题描述】:

我想创建一组文件夹,我想在其中将我的文件上传到 s3 存储桶中。 但是,我没有得到所需的文件名。 这是我的代码

s3 = boto3.resource('s3')

def upload_to_aws(local_file, bucket, s3_file):
    s3 = boto3.client('s3', aws_access_key_id=ACCESS_KEY,
                      aws_secret_access_key=SECRET_KEY)

    try:
        s3.upload_file(local_file, bucket, s3_file)
        print("Upload Successful")
        return True
    except FileNotFoundError:
        print("The file was not found")
        return False
    except NoCredentialsError:
        print("Credentials not available")
        return False

customer_name = "demo"
date = datetime.now().strftime('%d')
month = datetime.now().month
year = datetime.now().year


stack_path = "/home/ubuntu/pano/stack"    
for file in sorted(os.listdir(stack_path)):
    print(f"Uploading {file}")
    folders_path = f"{customer_name}/{year}/{month}/{date}"
    uploaded = upload_to_aws(f'/home/ubuntu/pano/stack/{file}', 'bucket-name1', '%s/%s' % (folders_path, file))

我希望文件夹是客户名称/年/月/日,我希望在其中上传文件。但是我得到的文件夹是 “顾客姓名/ ” “年/” “月/” “日期/” 我不想要文件夹名称中的反斜杠。我该怎么做?

编辑

我想要的文件夹具有以下路径 - 年/月/日/文件名.txt 但是,正在创建的路径具有以下文件夹名称 年//月//日//文件名.txt

每个文件夹名称都附有一个反斜杠。这些是我在我的存储桶中看到的目录

  1. 年/
  2. 月/
  3. 日期/

我想避免使用反斜杠和名称

【问题讨论】:

  • S3 中没有称为“文件夹”的概念。这些是帮助对文件进行分组的前缀。因此,您可以使用my/awesome/file/content.json 上传文件,而无需明确创建“文件夹”。
  • 在 S3 中,您使用 Key 存储对象。理论上它没有文件夹。您能否举一个文件名为“abc.txt”的示例并解释您的预期和正在发生的事情?
  • 以上所有的cmets都是真的,但我还是不明白你的问题是什么。你能详细解释一下吗?
  • @Azize 我已经在编辑中添加了详细信息

标签: python-3.x amazon-web-services amazon-s3 boto3


【解决方案1】:

这只是表示什么是“文件”或什么是“文件夹”。
但请记住,没有文件夹的概念,它只是一个对象键。

见下文,我正在使用您的代码。成功上传文件到bucket。

Python 3.8.0 (default, Feb 25 2021, 22:10:10) 
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> import boto3
>>> from datetime import datetime
>>> 
>>> def upload_to_aws(local_file, bucket, s3_file):
...     print("###", local_file, bucket, s3_file)
...     s3 = boto3.client('s3')
...     
...     try:
...         s3.upload_file(local_file, bucket, s3_file)
...         print("Upload Successful")
...         return True
...     except FileNotFoundError:
...         print("The file was not found")
...         return False
...     except NoCredentialsError:
...         print("Credentials not available")
...         return False
... 
>>> customer_name = "demo"
>>> date = datetime.now().strftime('%d')
>>> month = datetime.now().month
>>> year = datetime.now().year
>>> 
>>> 
>>> stack_path = "/tmp/test"
>>> for file in sorted(os.listdir(stack_path)):
...     print(f"Uploading {file}")
...     folders_path = f"{customer_name}/{year}/{month}/{date}"
...     uploaded = upload_to_aws(f'/tmp/test/{file}', 'test-bucket', '%s/%s' % (folders_path, file))
... 
Uploading file1
### /tmp/test/file1 test-bucket demo/2021/4/22/file1
Upload Successful
Uploading file2
### /tmp/test/file2 test-bucket demo/2021/4/22/file2
Upload Successful
Uploading file3
### /tmp/test/file3 test-bucket demo/2021/4/22/file3
Upload Successful
>>> exit()

现在让我们看看如何获​​取文件。请注意,文件的密钥正是您所期望的,所以不要在上面加倍 /

Python 3.8.0 (default, Feb 25 2021, 22:10:10) 
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import boto3
>>> s3 = boto3.client('s3')
>>> s3.get_object(Bucket='test-bucket', Key='demo/2021/4/22/file1')
{'ResponseMetadata': {'RequestId': 'RE...', 'HostId': 'eMmV3p+...', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': 'eMm...', 'x-amz-request-id': 'RE..', 'date': 'Thu, 22 Apr 2021 13:45:33 GMT', 'last-modified': 'Thu, 22 Apr 2021 13:41:09 GMT', 'etag': '"355..."', 'accept-ranges': 'bytes', 'content-type': 'binary/octet-stream', 'content-length': '11', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'AcceptRanges': 'bytes', 'LastModified': datetime.datetime(2021, 4, 22, 13, 41, 9, tzinfo=tzutc()), 'ContentLength': 11, 'ETag': '"35..."', 'ContentType': 'binary/octet-stream', 'Metadata': {}, 'Body': <botocore.response.StreamingBody object at 0x7f2b2ea8ddf0>}

来自 AWS CLI。在第一个输出中,您可以看到最后的 /,但这只是一个表示,请查看下面的完整对象键。

$ aws s3 ls s3://test-bucket/demo
                           PRE demo/

$ aws s3 ls s3://test-bucket/demo --recursive 
2021-04-22 10:41:09         11 demo/2021/4/22/file1
2021-04-22 10:41:09         11 demo/2021/4/22/file2
2021-04-22 10:41:10         11 demo/2021/4/22/file3

【讨论】:

    猜你喜欢
    • 2021-10-01
    • 2022-01-26
    • 2020-11-02
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    相关资源
    最近更新 更多