All Products
Search
Document Center

Object Storage Service:Check if an object exists (Python SDK V1)

Last Updated:Mar 19, 2026

Use bucket.object_exists(key) to check whether an object exists in a bucket. The method returns True if the object exists, or False if it does not.

Prerequisites

Before you begin, ensure that you have:

Check if an object exists

Method signature: bucket.object_exists(key)

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

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

# Set the endpoint for the region where your bucket is located.
# This example uses the China (Hangzhou) public endpoint.
# If you are accessing OSS from another Alibaba Cloud service in the same region, use the internal endpoint.
# For all regions and endpoints, see https://www.alibabacloud.com/help/en/oss/user-guide/regions-and-endpoints#concept-zt4-cvy-5db
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Required for V4 signatures. Set this to the region where your bucket is located.
region = "cn-hangzhou"

bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Specify the full path of the object, excluding the bucket name.
exists = bucket.object_exists("exampleobject.txt")

if exists:
    print("Object exists.")
else:
    print("Object does not exist.")

Usage notes

  • Return values: object_exists() returns True if the object exists, or False if it does not.

  • Object path: The full path passed to object_exists() must not include the bucket name.

  • Endpoint: The example uses the public endpoint for China (Hangzhou). To access OSS from another Alibaba Cloud service in the same region, use the internal endpoint instead. For the full list of regions and endpoints, see Regions and endpoints.

  • OSSClient initialization: The example creates an OSSClient instance using an OSS endpoint. To use a custom domain name or Security Token Service (STS) instead, see Initialization.