Creating/Uploading new file at Google Cloud Storage bucket using Python

ぐ巨炮叔叔 提交于 2020-12-01 07:18:48

问题


How to create new empty files in Google Cloud Storage using Python with client libraries available?

Or how to upload a new file to a selected bucket using blob function "upload_from_filename()" ? To initialize the blob object we should have file already in the cloud bucket, but I want to create a new file name, and copy the content from the file stored locally. I want to do this using python.

Thanks in advance


回答1:


First you need to load the library

import google.cloud.storage

Assuming you have a service account created and JSON file loaded somewhere, you need to create a client object

storage_client = google.cloud.storage.Client.from_service_account_json('JSON filepath')

Then you need to provide the create a bucket object

bucket = storage_client.get_bucket('bucket_name')

Now define the path within your bucket and the file name

d = 'path/name'

The blob method create the new file, also an object.

d = bucket.blob(d)

The upload_from_string method add the contents of the file. There are other methods allowing you to perform different tasks.

d.upload_from_string('V')

The first few steps take the longest to be ready the first time.

Good luck!




回答2:


If somebody is looking for the same thing, here is the solution. First you need to create/initialize bucket variable with the bucket name you want to create a new blob in. After that instead of calling blob you create blob using bucket.blob("filename"), this creates a new blob if the given filename is not there in the bucket already. Then you can use blob.create_from_filename("filename_which_you want to copy"), this will copy the contents to the blob created earlier for more detail solution you can read blob documentation here:

https://googlecloudplatform.github.io/google-cloud-python/stable/storage-blobs.html

Hope this will help someone. Below is the sample python code:

client=storage.Client();  
bucket=client.get_bucket('your bucket name');  
blob=bucket.blob('newfile you want to create')
blob.upload_from_filename('localdirectory/filename.mp4')


来源:https://stackoverflow.com/questions/43264664/creating-uploading-new-file-at-google-cloud-storage-bucket-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!