使用 Python 在 Google Cloud Storage 存储桶中创建/上传新文件 [英] Creating/Uploading new file at Google Cloud Storage bucket using Python
问题描述
如何使用 Python 和可用的客户端库在 Google Cloud Storage 中创建新的空文件?
How to create new empty files in Google Cloud Storage using Python with client libraries available?
或者如何使用 blob 函数upload_from_filename()"将新文件上传到选定的存储桶?要初始化 blob 对象,我们应该在云存储桶中已有文件,但我想创建一个新文件名,并从本地存储的文件中复制内容.我想用 python 来做这个.
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.
提前致谢
推荐答案
首先需要加载库
import google.cloud.storage
假设您创建了一个服务帐户并在某处加载了 JSON 文件,您需要创建一个客户端对象
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')
那么你需要提供创建一个bucket对象
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'
blob 方法创建新文件,也是一个对象.
The blob method create the new file, also an object.
d = bucket.blob(d)
upload_from_string 方法添加文件的内容.还有其他方法可以让您执行不同的任务.
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.
祝你好运!
这篇关于使用 Python 在 Google Cloud Storage 存储桶中创建/上传新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!