# What is the Python code related to collection actions for blender 2.8?

2.8 is new and I can't find how to:

• Create a new collection.

• Add selected object to collection "name here" .

• Add selected object to collection created in the same code.

Could someone show me how?

i found this and this in the API

• Who down voted this? This question is awesome. Get out of here, haters. Feb 6 '20 at 15:11

Here an example i made, it will place the active object to a new collection. it's a really simple example i hope it can help the beginner (like me) out there.

import bpy

obj = bpy.context.object
obj_old_coll = obj.users_collection #list of all collection the obj is in

new_coll = bpy.data.collections.new(name="COLLECTION TEST") #create new coll in data

for ob in obj_old_coll: #unlink from all  precedent obj collections


here another examples:

import bpy

A = bpy.context.object
A_old_coll = A.users_collection #list of all collection the obj is in

terrain_coll_name = "Scatter: ["+A.name+"]"+" Terrain"
if terrain_coll_name not in bpy.data.collections: #if this collection name is not in all collection already:
terrain_coll = bpy.data.collections.new(name=terrain_coll_name) #create new coll in data
else:
terrain_coll = bpy.data.collections[terrain_coll_name] #else let re use the already existing one

for ob in A_old_coll: #unlink from all  precedent obj collections


I found this question (and related links) useful, so thought I would respond here even though the original query is now quite old.

I found the code you have adapted quite hard to follow. Mainly because of my lack of Python experience but partly because of the additional checks (number of selected objects > 0 and create new collection if one doesn't already exist).

This version is less sophisticated, but is perhaps easier to follow and it resolves the [2] related error.

import bpy

#create list of collection names
CollList = ['Structure', 'Architecture', 'Biscuits']

#Find length of collection list (could just use '3' in this case, but I prefer to have a general case)
CollLen = len(CollList)

#create collections from the list
for x in range(0,CollLen):
y = bpy.data.collections.new(CollList[x])