- Documentation
Torch Object Storage
SDK Reference
Python
Introduction to typical scenes
Move and rename scenarios (Python SDK)
Introduction to typical scenes
Move and rename scenarios (Python SDK)
Move and rename scenarios (Python SDK)
If you need to rename files in a Bucket, you can copy the source object to the target object using the CopyObject API and then delete the source object using the DeleteObject API.
Rename a single object
The following code renames the object src-object to dest-object in the bucket bucket-test.
ak = os.getenv('TOS_ACCESS_KEY')
sk = os.getenv('TOS_SECRET_KEY')
endpoint = "your endpoint"
bucket_name = "bucket-test"
client = tos.TosClientV2(ak, sk, endpoint, region)
resp = client.copy_object('bucket-test', 'dest-object', 'bucket-test', 'src-object')
print('result status', resp.status_code)
resp = client.delete_object('bucket-test', 'src-object')
print('result status', resp.status_code)
except tos.exceptions.TosClientError as e:
print('fail with client error, message:{}, cause: {}'.format(e.message, e.cause))
except tos.exceptions.TosServerError as e:
print('fail with server error, code: {}'.format(e.code))
print('error with request id: {}'.format(e.request_id))
print('error with message: {}'.format(e.message))
print('error with http code: {}'.format(e.status_code))
print('error with ec: {}'.format(e.ec))
print('error with request url: {}'.format(e.request_url))
print('fail with unknown error: {}'.format(e))
Rename a directory
The following code renames the directory exampledir1/ to exampledir2/ in the bucket bucket-test.
ak = os.getenv('TOS_ACCESS_KEY')
sk = os.getenv('TOS_SECRET_KEY')
endpoint = "your endpoint"
bucket_name = 'bucket-test'
client = tos.TosClientV2(ak, sk, endpoint, region)
result = client.list_objects_type2(bucket_name, continuation_token=continuation_token, prefix=dir_1)
for iterm in result.contents:
new_key = dir_2 + new_key.removeprefix(dir_1)
client.copy_object(bucket_name, new_key, bucket_name, iterm.key)
client.delete_object(bucket_name, iterm.key)
truncated = result.is_truncated
continuation_token = result.next_continuation_token
Related documentation
Last updated: 2025.09.17 18:22:10