List Files in a Google Cloud Storage Bucket using Python
In this tutorial, we will learn how to retrieve a list of all objects (blobs) stored within a specific Cloud Storage bucket using Python. This is useful for auditing bucket content and building file browsers.
Python Code to List Files
We will use the list_blobs() method to retrieve objects stored inside a bucket.
Example: List files in a bucket.
Python
# Import required packages
from dotenv import load_dotenv
import os
from google.oauth2 import service_account
from google.cloud import storage
def main():
# Load environment variables from a .env file
load_dotenv()
# Read values from environment variables
credentials_path = os.getenv("GOOGLE_APPLICATION_CREDENTIALS")
project_name = os.getenv("project_id")
# Load service account credentials
credentials = service_account.Credentials.from_service_account_file(
credentials_path
)
# Create the Storage client
client = storage.Client(credentials=credentials, project=project_name)
# Define the bucket name
bucket_name = "new-bucket-via-python-sdk"
# List all blobs (files) in the bucket
blobs = client.list_blobs(bucket_name)
print(f"Files in bucket {bucket_name}:")
# Iterate through each file
for blob in blobs:
print(f"File Name: {blob.name}")
if __name__ == "__main__":
main() Key Steps Explained
- client.list_blobs(bucket_name): Returns an iterator over all objects in the specified bucket.
- blob.name: Retrieves the full path and name of each stored file.
- The loop prints each file available in the bucket.
Note: Cloud Storage uses a flat namespace. Objects containing slashes in their names simulate a folder structure.