# How can I store the name of selected objects in a text file?

I would like to create an automatic list of the objects that have been selected with the mouse click. So for example I have cube1, cube2, cube3, cube4.

I select them in the following order cube3, cube2, cube4, cube1 then a list on a text file shoud be generated in the order that they have been selected 3,2,4,1.

So the answer to this question is not as straight forward as you would expect. Blender is not storing the selection order for objects. It only stores the active object and a sorted list of all other objects. So what you really need is a way to catch all selection events. One way to do that is using a modal operator like this:

import bpy

class OBJECT_OT_record_selection(bpy.types.Operator):
"""Records the selection order while running and when finished with ESC saves it to //order.txt"""
bl_idname = "object.record_selection"
bl_label = "Record Selection"

origSel: None
selOrder: None

@classmethod
def poll(cls, context):
return context.mode == 'OBJECT'

def modal(self, context, event):
# Update selection
curSel = context.object

# On selecting new object
if curSel is not self.origSel:
self.report({'INFO'}, 'Selection was changed')
self.origSel = curSel
self.selOrder.append(context.object)
elif event.type in {'RIGHTMOUSE', 'ESC'}:
# Use this to save to an internal text data block
if "order.txt" not in bpy.data.texts:
bpy.data.texts.new("order.txt")
bpy.data.texts["order.txt"].clear()
bpy.data.texts["order.txt"].write('\n'.join([obj.name for obj in self.selOrder]))

# Use this for saving to a text file
#try:
#    with open(bpy.path.abspath("//order.txt"), 'w+') as f:
#        for obj in self.selOrder:
#            f.write("%s\n" % obj.name)
#    self.report({'INFO'}, 'Saved order to file at ./order.txt')
#except Exception:
#    self.report({'ERROR'}, 'Error while writing to file at ./order.txt')
return {'CANCELLED'}

return {'PASS_THROUGH'}

def invoke(self, context, event):
self.origSel = context.object
self.selOrder = []
if context.object is not None:
self.selOrder.append(context.object)
return {'RUNNING_MODAL'}

self.layout.operator(
OBJECT_OT_record_selection.bl_idname,
text="Record Selection",
icon='RESTRICT_SELECT_OFF')

def register():
bpy.utils.register_class(OBJECT_OT_record_selection)

def unregister():
bpy.utils.unregister_class(OBJECT_OT_record_selection)