How can I store the name of selected objects in a text file?
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):
    &quot;&quot;&quot;Records the selection order while running and when finished with ESC saves it to //order.txt&quot;&quot;&quot;
    bl_idname = &quot;object.record_selection&quot;
    bl_label = &quot;Record Selection&quot;

    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 &quot;order.txt&quot; not in bpy.data.texts:
                bpy.data.texts.new(&quot;order.txt&quot;)
            bpy.data.texts[&quot;order.txt&quot;].clear()
            bpy.data.texts[&quot;order.txt&quot;].write('\n'.join([obj.name for obj in self.selOrder]))
            
            # Use this for saving to a text file
            #try:
            #    with open(bpy.path.abspath(&quot;//order.txt&quot;), 'w+') as f:
            #        for obj in self.selOrder:
            #            f.write(&quot;%s\n&quot; % 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)
        context.window_manager.modal_handler_add(self)
        return {'RUNNING_MODAL'}


def add_object_button(self, context):
    self.layout.operator(
        OBJECT_OT_record_selection.bl_idname,
        text=&quot;Record Selection&quot;,
        icon='RESTRICT_SELECT_OFF')


def register():
    bpy.utils.register_class(OBJECT_OT_record_selection)
    bpy.types.VIEW3D_MT_select_object.append(add_object_button)


def unregister():
    bpy.utils.unregister_class(OBJECT_OT_record_selection)
    bpy.types.VIEW3D_MT_select_object.remove(add_object_button)


if __name__ == &quot;__main__&quot;:
    register()