-
Notifications
You must be signed in to change notification settings - Fork 1
/
aws_s3_blog_post.py
76 lines (51 loc) · 1.81 KB
/
aws_s3_blog_post.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import boto3
"""
medium blog post code to do basic boto3 commands to access s3, view buckets, view objects,
upload files from local, download files to local, delete objects, and delete buckets
"""
# connect to client / credentials
s3_client = boto3.resource('s3')
print(s3_client)
# s3.ServiceResource()
# create bucket and set bucket object
andre_bucket = s3_client.create_bucket(Bucket='andre.gets.buckets')
# view all bucket names
for bucket in s3_client.buckets.all():
print(bucket.name)
# add objects to a specific bucket
andre_bucket.put_object(Key='andre/added/a/new/object1')
andre_bucket.put_object(Key='andre/added/a/new/object2')
andre_bucket.put_object(Key='andre/added/a/new/object3')
# view newly uploaded data object
for obj in andre_bucket.objects.all():
print(obj.key)
# andre/added/a/new/object1
# andre/added/a/new/object2
# andre/added/a/new/object3
# upload local csv to a specific s3 bucket
local_file_path = '/Users/andreviolante/Desktop/data.csv'
key_object = 'andre/added/a/new/object/data.csv'
andre_bucket.upload_file(local_file_path, key_object)
# view newly uploaded data object
for obj in andre_bucket.objects.all():
print(obj.key)
# andre/added/a/new/object/data.csv
# andre/added/a/new/object1
# andre/added/a/new/object2
# andre/added/a/new/object3
# download an s3 file to local machine
filename = 'downloaded_s3_data.csv'
andre_bucket.download_file(key_object, filename)
# delete a specific object
andre_bucket.Object('andre/added/a/new/object2').delete()
for obj in andre_bucket.objects.all():
print(obj.key)
# delete the rest of objects in a bucket
andre_bucket.objects.delete()
for obj in andre_bucket.objects.all():
print(obj.key)
# delete a specific bucket
andre_bucket.delete()
# view all bucket names again
for bucket in s3_client.buckets.all():
print(bucket.name)