Listing Objects

This page shows you how to list the objects stored in your Cloud Storage buckets, which are ordered in the list lexicographically by name. For an overview of buckets and objects, read the Key Terms.

To list the objects in a bucket:

Console

  1. Open the Cloud Storage browser in the Google Cloud Platform Console.
    Open the Cloud Storage browser
  2. In the bucket list, select the bucket whose contents you want to view.

  3. Optionally, use the Filter by prefix... field to narrow the results in your bucket list to objects with the prefix you specify.

    Filter by prefix textbox.

gsutil

Use the gsutil ls command with the -r flag, replacing [VALUES_IN_BRACKETS] with the appropriate values:

gsutil ls -r gs://[BUCKET_NAME]/**

The response looks like the following example:

gs://[BUCKET_NAME]/[OBJECT_NAME1]
gs://[BUCKET_NAME]/[OBJECT_NAME2]
gs://[BUCKET_NAME]/[OBJECT_NAME3]
...

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation .

namespace gcs = google::cloud::storage;
[](gcs::Client client, std::string bucket_name) {
  for (gcs::ObjectMetadata const& meta : client.ListObjects(bucket_name)) {
    std::cout << "bucket_name=" << meta.bucket()
              << ", object_name=" << meta.name() << std::endl;
  }
}

C#

For more information, see the Cloud Storage C# API reference documentation .

The following sample lists all objects in a bucket:

private void ListObjects(string bucketName)
{
    var storage = StorageClient.Create();
    foreach (var storageObject in storage.ListObjects(bucketName, ""))
    {
        Console.WriteLine(storageObject.Name);
    }
}

The following sample lists objects with a given prefix:

private void ListObjects(string bucketName, string prefix,
    string delimiter)
{
    var storage = StorageClient.Create();
    var options = new ListObjectsOptions() { Delimiter = delimiter };
    foreach (var storageObject in storage.ListObjects(
        bucketName, prefix, options))
    {
        Console.WriteLine(storageObject.Name);
    }
}

Go

For more information, see the Cloud Storage Go API reference documentation .

The following sample lists all objects in a bucket:

it := client.Bucket(bucket).Objects(ctx, nil)
for {
	attrs, err := it.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		return err
	}
	fmt.Fprintln(w, attrs.Name)
}

The following sample lists objects with a given prefix:

// Prefixes and delimiters can be used to emulate directory listings.
// Prefixes can be used filter objects starting with prefix.
// The delimiter argument can be used to restrict the results to only the
// objects in the given "directory". Without the delimeter, the entire  tree
// under the prefix is returned.
//
// For example, given these blobs:
//   /a/1.txt
//   /a/b/2.txt
//
// If you just specify prefix="a/", you'll get back:
//   /a/1.txt
//   /a/b/2.txt
//
// However, if you specify prefix="a/" and delim="/", you'll get back:
//   /a/1.txt
it := client.Bucket(bucket).Objects(ctx, &storage.Query{
	Prefix:    prefix,
	Delimiter: delim,
})
for {
	attrs, err := it.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		return err
	}
	fmt.Fprintln(w, attrs.Name)
}

Java

For more information, see the Cloud Storage Java API reference documentation .

The following sample lists all objects in a bucket:

Page<Blob> blobs = bucket.list();
for (Blob blob : blobs.iterateAll()) {
  // do something with the blob
}

The following sample lists objects with a given prefix:

Page<Blob> blobs =
    storage.list(
        bucketName, BlobListOption.currentDirectory(), BlobListOption.prefix(directory));
for (Blob blob : blobs.iterateAll()) {
  // do something with the blob
}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation .

The following sample lists all objects in a bucket:

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Lists files in the bucket
const [files] = await storage.bucket(bucketName).getFiles();

console.log('Files:');
files.forEach(file => {
  console.log(file.name);
});

The following sample lists objects with a given prefix:

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const prefix = 'Prefix by which to filter, e.g. public/';
// const delimiter = 'Delimiter to use, e.g. /';

/**
 * This can be used to list all blobs in a "folder", e.g. "public/".
 *
 * The delimiter argument can be used to restrict the results to only the
 * "files" in the given "folder". Without the delimiter, the entire tree under
 * the prefix is returned. For example, given these blobs:
 *
 *   /a/1.txt
 *   /a/b/2.txt
 *
 * If you just specify prefix = '/a', you'll get back:
 *
 *   /a/1.txt
 *   /a/b/2.txt
 *
 * However, if you specify prefix='/a' and delimiter='/', you'll get back:
 *
 *   /a/1.txt
 */
const options = {
  prefix: prefix,
};

if (delimiter) {
  options.delimiter = delimiter;
}

// Lists files in the bucket, filtered by a prefix
const [files] = await storage.bucket(bucketName).getFiles(options);

console.log('Files:');
files.forEach(file => {
  console.log(file.name);
});

PHP

For more information, see the Cloud Storage PHP API reference documentation .

The following sample lists all objects in a bucket:

use Google\Cloud\Storage\StorageClient;

/**
 * List Cloud Storage bucket objects.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 *
 * @return void
 */
function list_objects($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    foreach ($bucket->objects() as $object) {
        printf('Object: %s' . PHP_EOL, $object->name());
    }
}

The following sample lists objects with a given prefix:

use Google\Cloud\Storage\StorageClient;

/**
 * List Cloud Storage bucket objects with specified prefix.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 *
 * @return void
 */
function list_objects_with_prefix($bucketName, $prefix)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $options = ['prefix' => $prefix];
    foreach ($bucket->objects($options) as $object) {
        printf('Object: %s' . PHP_EOL, $object->name());
    }
}

Python

For more information, see the Cloud Storage Python API reference documentation .

The following sample lists all objects in a bucket:

def list_blobs(bucket_name):
    """Lists all the blobs in the bucket."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)

    blobs = bucket.list_blobs()

    for blob in blobs:
        print(blob.name)

The following sample lists objects with a given prefix:

def list_blobs_with_prefix(bucket_name, prefix, delimiter=None):
    """Lists all the blobs in the bucket that begin with the prefix.

    This can be used to list all blobs in a "folder", e.g. "public/".

    The delimiter argument can be used to restrict the results to only the
    "files" in the given "folder". Without the delimiter, the entire tree under
    the prefix is returned. For example, given these blobs:

        /a/1.txt
        /a/b/2.txt

    If you just specify prefix = '/a', you'll get back:

        /a/1.txt
        /a/b/2.txt

    However, if you specify prefix='/a' and delimiter='/', you'll get back:

        /a/1.txt

    """
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)

    blobs = bucket.list_blobs(prefix=prefix, delimiter=delimiter)

    print('Blobs:')
    for blob in blobs:
        print(blob.name)

    if delimiter:
        print('Prefixes:')
        for prefix in blobs.prefixes:
            print(prefix)

Ruby

For more information, see the Cloud Storage Ruby API reference documentation .

The following sample lists all objects in a bucket:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project_id: project_id
bucket  = storage.bucket bucket_name

bucket.files.each do |file|
  puts file.name
end

The following sample lists objects with a given prefix:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# prefix      = "Filter results to files whose names begin with this prefix"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project_id: project_id
bucket  = storage.bucket bucket_name
files   = bucket.files prefix: prefix

files.each do |file|
  puts file.name
end

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the JSON API, replacing [VALUES_IN_BRACKETS] with the appropriate values:
    curl -X GET -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]/o"

    You can use a prefix=[PREFIX] query string parameter to limit results to objects that have the specified prefix.

See the Objects: list JSON reference page for more information.

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the XML API, replacing [VALUES_IN_BRACKETS] with the appropriate values:
    curl -X GET -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        "https://storage.googleapis.com/[BUCKET_NAME]"

    You can use a prefix=[PREFIX] query string parameter to limit results to objects that have the specified prefix.

See the List Objects XML reference page for more information.

What's next

¿Te sirvió esta página? Envíanos tu opinión:

Enviar comentarios sobre…

¿Necesitas ayuda? Visita nuestra página de asistencia.