python操作s3 -- boto2.x

以下是python操作s3常用方法:

boto s3手册:http://boto.readthedocs.org/en/latest/ref/s3.html

boto s3快速入门:http://boto.readthedocs.org/en/latest/s3_tut.html

import boto
from boto.s3.key import Key

#高级连接,当然你需要配置好YOUR_ACCESS_KEY,YOUR_SECRET_KEY,我这里是配好了
conn = boto.connect_s3()

#创建一个存储桶
conn.create_bucket('yourbucket')
conn.create_bucket('yourbucket', location=Location.USWest)

#访问一个存储桶
bucket = conn.get_bucket('yourbucket')
exists = conn.lookup('yourbucket')

#向s3上存储数据, 数据来源可以是file、stream、or string,下面为从文件获取数据保存到s3上的test.txt文件中
key = Key(bucket, 'hadoop/data_log/test.txt')
key.set_contents_from_file('/tmp/hello.txt')
#读取s3上文件中的内容,返回string,当然还有其他形式,看源码
key.get_contents_as_string()

#删除一个存储桶,在删除存储桶本身时必须删除该存储桶内的所有key
for key in bucket:
    key.delete()
bucket.delete()

#迭代遍历buckets and keys
for bucket in conn:
    for key in bucket:
        print key.name

#一个判断文件夹中是否有文件的方法
rs = bucket.get_all_keys(prefix=rel_path)
if len(rs)>0:
    print '有文件'
else:
    print '为空'
#例如:要判断 path=s3://data/hadoop/data_log/20160301/01/文件夹下是否有文件时,rel_path的取值:rel_path = path[10:]

  

原文地址:https://www.cnblogs.com/yxpblog/p/5332162.html