All Products
Search
Document Center

Object Storage Service:List objects via OSS SDK for Python 1.0

Last Updated:Mar 20, 2026

OSS SDK for Python provides two built-in iterators to list objects in a bucket: ObjectIteratorV2 and ObjectIterator. Both automatically handle multi-page results across multiple API calls — no matter how many objects are in the bucket, a single for loop retrieves them all without any manual pagination logic.

Choose an iterator

ObjectIteratorV2ObjectIterator
Based onListObjectsV2 (GetBucketV2)GetBucket (ListObjects)
PaginationToken-based (continuation_token)Marker-based (marker)
Owner informationOmitted by default; opt in with fetch_owner=TrueReturned by default
Versioning-enabled bucketsFull supportLimited support
Minimum SDK version2.12.0

Use ObjectIteratorV2 for new projects. Compared to ObjectIterator, it omits owner information by default (smaller response payloads), uses a more reliable token-based continuation model, and fully supports versioning-enabled buckets.

ObjectIteratorV2 constructor

oss2.ObjectIteratorV2(bucket, prefix='', delimiter='', continuation_token='',
                      start_after='', fetch_owner=False, encoding_type='url',
                      max_keys=100, max_retries=None, headers=None)

Click to view the parameter descriptions

ParameterTypeRequiredDefaultDescription
bucketoss2.BucketYesThe initialized bucket object
prefixstrNo''Filter results to objects whose names start with this string. An empty string returns all objects. For example, if the bucket contains logs/day1, logs/day2, and notes.txt, setting prefix='logs/' returns only logs/day1 and logs/day2.
delimiterstrNoGroup object names by a common character. Set to / to simulate a folder structure.
continuation_tokenstrNo''Resume a previous listing. Pass an empty string to start from the beginning.
start_afterstrNoReturn only objects whose names are lexicographically after this string. The named object itself is excluded. For example, if the bucket contains a.txt, b.txt, and c.txt, setting start_after='b.txt' returns only c.txt.
fetch_ownerboolNoFalseSet to True to include owner information in results.
encoding_typestrNo'url'Encoding applied to object names in the response.
max_keysintNo100Maximum number of objects returned per API call. Maximum value: 1000.
max_retriesintNoNoneMaximum number of retries on request failure.

ObjectIterator constructor

oss2.ObjectIterator(bucket, prefix='', delimiter='', marker='',
                    max_keys=100, max_retries=None, headers=None)

Click to view the parameter descriptions

ParameterTypeRequiredDefaultDescription
bucketoss2.BucketYesThe initialized bucket object
prefixstrNo''Filter results to objects whose names start with this string. An empty string returns all objects.
delimiterstrNoGroup object names by a common character. Set to / to simulate a folder structure.
markerstrNo''Return only objects whose names are lexicographically after this string. The named object itself is excluded.
max_keysintNo100Maximum number of objects returned per API call. Maximum value: 1000.
max_retriesintNoNoneMaximum number of retries on request failure.

Prerequisites

Before you begin, make sure that you have:

  • OSS SDK for Python installed and access credentials configured as environment variables. See Quick start with OSS SDK for Python.

  • The oss:ListObjects permission. An Alibaba Cloud account has this permission by default. If you use a Resource Access Management (RAM) user or RAM role, grant the permission explicitly.

Code examples

All examples use oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) to load access credentials from environment variables and operate on a bucket named example-bucket in the cn-hangzhou region.

The iterators handle all pagination internally. When a bucket contains more than 1,000 objects, the iterator automatically issues additional API calls and continues yielding results — you do not need to manage continuation_token or marker manually.

List all objects

ObjectIteratorV2 (recommended)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def main():
    # Load access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)

    # List all objects in the bucket.
    print("List all objects:")
    for obj in oss2.ObjectIteratorV2(bucket):
        print(f"Object name: {obj.key}, Size: {obj.size} bytes")

if __name__ == "__main__":
    main()

To include owner information, set fetch_owner=True:

# List all objects with owner information.
for obj in oss2.ObjectIteratorV2(bucket, fetch_owner=True):
    print(f"Object name: {obj.key}")
    print(f"Owner name: {obj.owner.display_name}")
    print(f"Owner ID: {obj.owner.id}")

ObjectIterator

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def main():
    # Load access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)

    # List all objects in the bucket.
    print("List all objects:")
    for obj in oss2.ObjectIterator(bucket):
        print(f"Object name: {obj.key}, Size: {obj.size} bytes")

if __name__ == "__main__":
    main()

List a specific number of objects

Use itertools.islice to cap the total number of objects returned.

ObjectIteratorV2 (recommended)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from itertools import islice

def main():
    # Load access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)

    # List the first 10 objects in the bucket.
    print("List the first 10 objects:")
    for obj in islice(oss2.ObjectIteratorV2(bucket), 10):
        print(f"Object name: {obj.key}")

if __name__ == "__main__":
    main()

ObjectIterator

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from itertools import islice

def main():
    # Load access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)

    # List the first 10 objects in the bucket.
    print("List the first 10 objects:")
    for obj in islice(oss2.ObjectIterator(bucket), 10):
        print(f"Object name: {obj.key}")

if __name__ == "__main__":
    main()

List objects with a specific prefix

Assume the bucket contains: oss.jpg, fun/test.jpg, fun/movie/001.avi, and fun/movie/007.avi.

Setting prefix='fun/' returns all objects whose names start with fun/, including objects in subdirectories.

ObjectIteratorV2 (recommended)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def main():
    # Load access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)

    # List all objects in the fun folder, including objects in its subdirectories.
    print("List all objects with the prefix fun/:")
    for obj in oss2.ObjectIteratorV2(bucket, prefix='fun/'):
        print(f"Object name: {obj.key}")

if __name__ == "__main__":
    main()

Expected output:

List all objects with the prefix fun/:
Object name: fun/
Object name: fun/movie/
Object name: fun/movie/001.avi
Object name: fun/movie/007.avi
Object name: fun/test.jpg

ObjectIterator

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def main():
    # Load access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)

    # List all objects in the fun folder, including objects in its subdirectories.
    print("List all objects with the prefix fun/:")
    for obj in oss2.ObjectIterator(bucket, prefix='fun/'):
        print(f"Object name: {obj.key}")

if __name__ == "__main__":
    main()

Expected output:

List all objects with the prefix fun/:
Object name: fun/
Object name: fun/movie/
Object name: fun/movie/001.avi
Object name: fun/movie/007.avi
Object name: fun/test.jpg

List objects and subdirectories in a specific directory

OSS does not have real folders. All data is stored as objects. A folder in OSS is a zero-byte object whose name ends with /. The OSS console displays such objects as folders.

Combine prefix and delimiter to browse a single directory level without recursing into subdirectories:

  • prefix='fun/' alone: returns all objects under fun/, including those in subdirectories.

  • prefix='fun/' with delimiter='/': returns only the objects and subfolder names directly inside fun/, not the contents of those subfolders.

Use obj.is_prefix() to distinguish subfolder entries from object entries in the results.

ObjectIteratorV2 (recommended)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def main():
    # Load access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)

    # List the objects and subfolder names in the fun folder, but not the objects within the subfolders.
    print("List objects and subdirectories in the fun directory:")
    for obj in oss2.ObjectIteratorV2(bucket, prefix='fun/', delimiter='/', start_after='fun/'):
        # Use the is_prefix method to determine whether the obj is a folder.
        if obj.is_prefix():
            print(f"Subdirectory: {obj.key}")
        else:
            print(f"Object: {obj.key}")

if __name__ == "__main__":
    main()

Expected output:

List objects and subdirectories in the fun directory:
Subdirectory: fun/movie/
Object: fun/test.jpg

ObjectIterator

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def main():
    # Load access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)

    # List the objects and subfolder names in the fun folder, but not the objects within the subfolders.
    print("List objects and subdirectories in the fun directory:")
    for obj in oss2.ObjectIterator(bucket, prefix='fun/', delimiter='/', marker='fun/'):
        # Use the is_prefix method to determine whether the obj is a folder.
        if obj.is_prefix():
            print(f"Subdirectory: {obj.key}")
        else:
            print(f"Object: {obj.key}")

if __name__ == "__main__":
    main()

Expected output:

List objects and subdirectories in the fun directory:
Subdirectory: fun/movie/
Object: fun/test.jpg

List objects after a specific start position

Assume the bucket contains: x1.txt, x2.txt, z1.txt, and z2.txt.

Setting start_after='x2.txt' (V2) or marker='x2.txt' (V1) returns all objects lexicographically after x2.txt. The named object itself is not included.

ObjectIteratorV2 (recommended)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def main():
    # Load access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)

    # List all objects after x2.txt (excluding x2.txt itself).
    print("List all objects after x2.txt:")
    for obj in oss2.ObjectIteratorV2(bucket, start_after="x2.txt"):
        print(f"Object name: {obj.key}")

if __name__ == "__main__":
    main()

Expected output:

List all objects after x2.txt:
Object name: z1.txt
Object name: z2.txt

ObjectIterator

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def main():
    # Load access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)

    # List all objects after x2.txt (excluding x2.txt itself).
    print("List all objects after x2.txt:")
    for obj in oss2.ObjectIterator(bucket, marker="x2.txt"):
        print(f"Object name: {obj.key}")

if __name__ == "__main__":
    main()

Expected output:

List all objects after x2.txt:
Object name: z1.txt
Object name: z2.txt

Get the size of objects in a specific directory

The following example calculates the total size of each folder in the root directory by iterating over its objects recursively.

ObjectIteratorV2 (recommended)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def calculate_folder_size(bucket, folder):
    """Calculate the total size of a specified folder."""
    total_size = 0
    for obj in oss2.ObjectIteratorV2(bucket, prefix=folder):
        total_size += obj.size
    return total_size

def main():
    # Load access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)

    # List all objects and folders in the root directory and display their sizes.
    print("List the sizes of objects and folders in the root directory:")
    for obj in oss2.ObjectIteratorV2(bucket, delimiter='/'):
        if obj.is_prefix():
            # Calculate the total size of the folder.
            folder_size = calculate_folder_size(bucket, obj.key)
            print(f"Directory: {obj.key}, Size: {folder_size} bytes")
        else:
            # Display the object size directly.
            print(f"Object: {obj.key}, Size: {obj.size} bytes")

if __name__ == "__main__":
    main()

ObjectIterator

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

def calculate_folder_size(bucket, folder):
    """Calculate the total size of a specified folder."""
    total_size = 0
    for obj in oss2.ObjectIterator(bucket, prefix=folder):
        total_size += obj.size
    return total_size

def main():
    # Load access credentials from environment variables.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    # Set the endpoint and region where the bucket is located.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    region = "cn-hangzhou"
    # Initialize the bucket.
    bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)

    # List all objects and folders in the root directory and display their sizes.
    print("List the sizes of objects and folders in the root directory:")
    for obj in oss2.ObjectIterator(bucket, delimiter='/'):
        if obj.is_prefix():
            # Calculate the total size of the folder.
            folder_size = calculate_folder_size(bucket, obj.key)
            print(f"Directory: {obj.key}, Size: {folder_size} bytes")
        else:
            # Display the object size directly.
            print(f"Object: {obj.key}, Size: {obj.size} bytes")

if __name__ == "__main__":
    main()