-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGCP_Python_Access.py
62 lines (46 loc) · 1.74 KB
/
GCP_Python_Access.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
"""Programatically interact with a Google Cloud Storage bucket."""
from google.cloud import storage
from os import environ
#Create and Delete bucket
create_bucket('my_bucket_name') #creates a new bucket with the given name.
bucket.delete() #deletes an existing bucket.
# Data
localFolder = r'/content/drive/MyDrive/ColabNotebooks/PDFFiles/'
storage_client = storage.Client()
bucket = storage_client.get_bucket('eattachments')
print(bucket)
#Upload Files
from os import listdir
from os.path import isfile, join
...
def upload_files(bucketName):
"""Upload files to GCP bucket."""
files = [f for f in listdir(localFolder) if isfile(join(localFolder, f))]
for file in files:
localFile = localFolder + file
blob = bucket.blob(file)
blob.upload_from_filename(localFile)
return f'Uploaded {files} to "{bucketName}" bucket.'
#ListFiles
def list_files(bucketName):
"""List all files in GCP bucket."""
files = bucket.list_blobs()
fileList = [file.name for file in files if '.' in file.name]
return fileList
#Download Files
from random import randint
def download_random_file(bucketName, localFolder):
"""Download random file from GCP bucket."""
fileList = list_files(bucketName)
for files in range(len(fileList)):
blob = bucket.blob(fileList[files])
fileName = blob.name.split('/')[-1]
blob.download_to_filename(localFolder + fileName)
return f'{fileList} downloaded from bucket.'
#Delete Files
def delete_file(bucketName):
"""Delete file from GCP bucket."""
fileList = list_files(bucketName)
for files in range(len(fileList)):
bucket.delete_blob(fileList[files])
return f'{fileList} deleted from bucket.'