20

I want to rename a large number of items. Doing so manually could take quite some time. I want to use python to rename the object. To find out the python command for renaming I renamed an object manually and looked in the console for the echoed command. The command was:

bpy.ops.object.select_all(action='TOGGLE')

This command does not seem to be the correct command for renaming. It does not even contain the new name in the command. I also tried to look up the python command reference for the name, but the link was a dead end.

How can I rename an object using python?

stacker
  • 38,549
  • 31
  • 141
  • 243
Vader
  • 14,680
  • 16
  • 74
  • 110

2 Answers2

28

You can access them by iterating and assign the name property:

import bpy

for obj in bpy.context.selected_objects:
    obj.name = "newName"

Blender automatically add .001, .002 and so on to newName if another datablock of same type and name already exists. You may need to check a name pattern within the for-loop.

Another example - rename all Mesh objects in current scene that start with C (e.g. Cube, case insensitive):

for obj in bpy.context.scene.objects:
    if obj.type == 'MESH' and obj.name.lower().startswith("c")
        obj.name = "newName"
CodeManX
  • 29,298
  • 3
  • 89
  • 128
stacker
  • 38,549
  • 31
  • 141
  • 243
1

In case your object has obj.data, make sure you change the name under .data too:

for obj in bpy.context.selected_objects:
    obj.name = "newName"
    obj.data.name = "newName"

Objects such as empties do not have data.

Amir
  • 3,074
  • 2
  • 29
  • 55