This document describes how to store and retrieve data using the Cloud Storage client library. It assumes that you completed the tasks described in Setting up for Cloud Storage to activate a Cloud Storage bucket and download the client libraries. It also assumes that you know how to build an App Engine application.
For additional code samples, see Cloud Storage client libraries
Required imports
Use the code snippet below for accessing Cloud Storage using the client library:
Specifying the Cloud Storage bucket
Before doing any operations in Cloud Storage, you need to supply the bucket name.The easiest way to do specify a bucket name is to use the default bucket for your project.
The call to get_default_gcs_bucket_name
succeeds only if you have created
the default bucket
for your project.
Writing to Cloud Storage
The following sample shows how to write to the bucket:
Note the following:
In the call to open the file for write, the sample specifies certain Cloud Storage headers that write custom metadata for the file; this metadata can be retrieved using
cloudstorage.stat()
. You can find the list of supported headers in thecloudstorage.open()
reference.The
x-goog-acl
header is not set. That means the default Cloud Storage ACL of public read is going to be applied to the object when it is written to the bucket.Ensure you invoke the function to close the file after you finish the write. If you don't do this, the file is not written to Cloud Storage. Be aware that after you call the Python file function
close()
, you cannot append to the file. If you need to modify a file, you'll have to call the Python file functionopen()
to open the file again in write mode, which does an overwrite, not an append.
Reading from Cloud Storage
The following sample shows how to read a full file from the bucket:
In both examples, the blob_name
argument that you pass to
cloudstorage.open()
is the path to your file in
YOUR_BUCKET_NAME/PATH_IN_GCS
format. Note
that the default for cloudstorage.open()
is read-only mode. You do not
need to specify a mode when opening a file to read it.
Listing bucket contents
The sample code shows how to page through a bucket with blob
type content :
Note that the complete file name is displayed as one string without directory
delimiters. If you want to display the file with its more recognizable directory
hierarchy, set the delimiter
parameter to the directory delimiter you want to
use.
Deleting files in Cloud Storage
The code below demonstrates how to delete a file from Cloud Storage using the
cloudstorage.delete()
method (imported as gcs
).
This example cleans up the files that were written to the bucket in the Writing to Cloud Storage section.
What's next
- Visit the API Reference documentation.
- See the Cloud Storage documentation for more guides and tutorials.