8

I have a scene with 2 collections of 4 objects each. I am trying to get all collection names and their objects' names. Unfortunately, info panel nor python hints have not been helpful to find the command.

How do I get a list of all collections' names? How do I get a list of all objects' names in a given collection?

brockmann
  • 12,613
  • 4
  • 50
  • 93
Student
  • 125
  • 1
  • 1
  • 4

2 Answers2

15

You can access all collections through bpy.data.collections. The objects within the collection (and child collections) are given by bpy.data.collections.all_objects. This is documented in the BlendData types and the documentation of the collection type.

A little example script for printing the content of the collections:

import bpy

for collection in bpy.data.collections: print(collection.name) for obj in collection.all_objects: print("obj: ", obj.name)

brockmann
  • 12,613
  • 4
  • 50
  • 93
Robert Gützkow
  • 25,622
  • 3
  • 47
  • 78
10

Some python console code

The python console is a great way to learn how the API works. For convenience C = bpy.context and D = bpy.data

Using simply the default file

enter image description here

All collections and all objects in each.

>>> for col in D.collections:
...     col.name, col.objects[:]
...     
('Collection 1', [bpy.data.objects['Cube'], bpy.data.objects['Lamp'], bpy.data.objects['Camera']])

or similarly

>>> for col in D.collections:
...     col.name
...     for o in col.objects:
...         o.name
...         
'Collection 1'
'Cube'
'Lamp'
'Camera'

Note the scene's top level or "master collection" is not listed above.

>>> C.scene.collection
bpy.data.collections['Master Collection']

Any objects in this collection? No, but if we link objects to it context.scene.collections.link(ob) there could be.

>>> C.scene.collection.objects[:]
[]

Worth mentioning the all_objects will recurse through and list all descendants (children, grandchildren, ...) collection's objects. In this case the child collection is "Collection 1"

>>> C.scene.collection.all_objects[:]
[bpy.data.objects['Cube'], bpy.data.objects['Lamp'], bpy.data.objects['Camera']]

Iterate through master collection's child collections, and list their objects.

>>> for col in C.scene.collection.children:
...     col.name, col.objects[:]
...     
('Collection 1', [bpy.data.objects['Cube'], bpy.data.objects['Lamp'], bpy.data.objects['Camera']])
batFINGER
  • 84,216
  • 10
  • 108
  • 233
  • Sorry batFINGER, your comment is very interesting and gives more knowledge than gtzkw's. However, he/she answered first and the answer solve my problem so I must give the point to that user. I am a new user and I do not have enough reputation to mark it as useful. Thank you for sharing your knowledge! – Student Jul 10 '19 at 07:53
  • aren't coll in D also potentially deleted "non-existent" collections? – Fox Oct 01 '19 at 00:09