# How do I create a text file from the selected objects containing name and collection?

I'm trying to do something similar as in this post, but instead of all dimensions from each object I want to know to which collection they belong.

The part of the code I changed was:

selection = bpy.context.selected_objects

# iterate through the selected objects
for sel in selection:
# get collection to which the object belongs
col = bpy.context.collection
# write the selected object's name and dimensions to a string
result += "%s, %s" % (sel.name, col.name)


However, this seems to loop over the collections that are inside of the selected objects instead of the other way around. How do I change my code to see the collection the objects belongs to?

• Pretty close but the collection name would be the same for all objects (context.collection is the active one). How to get the collection of the object: blender.stackexchange.com/a/134789/31447 Jul 23, 2021 at 15:32
• That works, thank you! Jul 23, 2021 at 15:49

check this out:

import bpy

for eachCol in bpy.data.collections:

print("Collection:", eachCol.name)

for eachObject in eachCol.objects:

print("  ", eachObject.name)


Test result:

or if you only want the info about the selected objects:

import bpy

selected = bpy.context.selected_objects

for eachSel in selected:

for eachCol in bpy.data.collections:
for eachObject in eachCol.objects:

if eachObject == eachSel:

print(eachObject.name, "is in", eachCol.name)


test result: