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
ObjectIteratorV2 | ObjectIterator | |
|---|---|---|
| Based on | ListObjectsV2 (GetBucketV2) | GetBucket (ListObjects) |
| Pagination | Token-based (continuation_token) | Marker-based (marker) |
| Owner information | Omitted by default; opt in with fetch_owner=True | Returned by default |
| Versioning-enabled buckets | Full support | Limited support |
| Minimum SDK version | 2.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)ObjectIterator constructor
oss2.ObjectIterator(bucket, prefix='', delimiter='', marker='',
max_keys=100, max_retries=None, headers=None)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:ListObjectspermission. 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 managecontinuation_tokenormarkermanually.
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.jpgObjectIterator
#!/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.jpgList 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 underfun/, including those in subdirectories.prefix='fun/'withdelimiter='/': returns only the objects and subfolder names directly insidefun/, 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.jpgObjectIterator
#!/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.jpgList 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.txtObjectIterator
#!/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.txtGet 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()