【问题标题】:Uploading files to aws s3 bucket with boto3(python 3.x) maintaining the file structure?使用boto3(python 3.x)将文件上传到aws s3存储桶维护文件结构?
【发布时间】:2018-11-02 20:05:26
【问题描述】:

我想将文件从磁盘上传到维护不同文件夹结构的 aws s3 存储桶。我可以制作与磁盘上相同的结构,但需要对结构进行一些更改。

磁盘上的文件夹结构为:/home/userdata/uploaded_folder/uploaded_file

我想在 aws 存储桶上维护的文件夹(键)结构是:

/userdata/uploaded_folder/uploaded_file/ 

我现在的代码是这样的:

from boto.s3.connection import S3Connection
from boto.s3.key import Key
import os

conn = S3Connection()
path = '/home/userdata/'
bucket = conn.get_bucket('myBuck')

for root, dirs, files in os.walk(path):
    for name in files:
        #print(root)
        path = root.split(os.path.sep)[1:]
        path.append(name)
        #print(path)
        key_id = os.path.join(*path)
        k = Key(bucket)
        k.key = key_id
        #print(key_id)
        #k.set_contents_from_filename(os.path.join(root, name))

上面的代码在桶中建立了精确的结构。如何改变路径?

【问题讨论】:

    标签: python-3.x boto3


    【解决方案1】:

    正确的行

    path = root.split(os.path.sep)[1:]
    

    path = root.split(os.path.sep)[2:]
    

    root.split(os.path.sep) 中的第一个元素是 '' 而不是 'home'

    【讨论】:

    • 是的,我试过了,但后来我无法使用path。如果我将path 与最后一行k.set_contents_from_filename(os.path.join(root, name)) 一起使用,我会收到错误消息。尝试使用path 代替root,它不会工作。
    • 基本上要做的事情是这样的:s3.upload_file(disk_path, bucket_name, full_path_to_s3)。我无法做到这一点。
    猜你喜欢
    • 1970-01-01
    • 2018-04-25
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多