use*_*539 9 amazon-s3 amazon-ec2 boto amazon-web-services python-2.7
我已经连接到实例,我想将从我的python脚本生成的文件直接上传到S3.我试过这个:
import boto
s3 = boto.connect_s3()
bucket = s3.get_bucket('alexandrabucket')
from boto.s3.key import Key
key = bucket.new_key('s0').set_contents_from_string('some content')
Run Code Online (Sandbox Code Playgroud)
但这是在创建一个带有上下文"相同内容"的新文件s0,而我想将目录s0上传到mybucket.
我也看了s3put,但我没有得到我想要的东西.
小智 22
以下函数可用于通过 boto 将目录上传到 s3。
def uploadDirectory(path,bucketname):
for root,dirs,files in os.walk(path):
for file in files:
s3C.upload_file(os.path.join(root,file),bucketname,file)
Run Code Online (Sandbox Code Playgroud)
提供目录和存储桶名称的路径作为输入。文件直接放入存储桶中。更改 upload_file() 函数的最后一个变量以将它们放在“目录”中。
Tob*_*nst 10
s3fs 包提供了很好的功能来处理这种情况
s3_file = s3fs.S3FileSystem()
local_path = "some_dir_path/some_dir_path/"
s3_path = "bucket_name/dir_path"
s3_file.put(local_path, s3_path, recursive=True)
Run Code Online (Sandbox Code Playgroud)
我根据@JDPTET 的反馈构建了该函数,但是,
os.path.normpath def upload_folder_to_s3(s3bucket, inputDir, s3Path):
print("Uploading results to s3 initiated...")
print("Local Source:",inputDir)
os.system("ls -ltR " + inputDir)
print("Dest S3path:",s3Path)
try:
for path, subdirs, files in os.walk(inputDir):
for file in files:
dest_path = path.replace(inputDir,"")
__s3file = os.path.normpath(s3Path + '/' + dest_path + '/' + file)
__local_file = os.path.join(path, file)
print("upload : ", __local_file, " to Target: ", __s3file, end="")
s3bucket.upload_file(__local_file, __s3file)
print(" ...Success")
except Exception as e:
print(" ... Failed!! Quitting Upload!!")
print(e)
raise e
s3 = boto3.resource('s3', region_name='us-east-1')
s3bucket = s3.Bucket("<<s3bucket_name>>")
upload_folder_to_s3(s3bucket, "<<Local Folder>>", "<<s3 Path>>")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21171 次 |
| 最近记录: |