This topic describes how to download objects from a bucket to a file.

Sample code

The following code provides an example on how to download exampleobject.txt from the testfolder directory in examplebucket to examplefile.txt in the D:\localpath path.

# -*- coding: utf-8 -*-
import oss2

# Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# In this example, the endpoint of the China (Hangzhou) region is used. Specify the endpoint based on your business requirements. 
# Specify the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, '', 'examplebucket')

# Specify the full path of the object. The path cannot contain the bucket name. Example: testfolder/exampleobject.txt. 
# Download the object to your local computer and save the object to the specified local path D:\\localpath\\examplefile.txt. If the specified local file exists, the object to download overwrites the file. Otherwise, a file is created. 
bucket.get_object_to_file('testfolder/exampleobject.txt', 'D:\\localpath\\examplefile.txt')        


  • For more information about the complete sample code that is used to download objects to local files, visit GitHub.
  • For more information about the API operation that you can call to download objects to local files, see GetObject.