Selection of object using command not working I wrote a script that imports and modifys two objects. It works as following: The script imports an .obj and makes some modifactions. The position of the object stays the same. After the modifications, the same .obj is imported again. Then the last imported object is selected and Boolean/Difference/Object1 used.

The Boolean works without problems, when I run the script till the object is imported again and I select the this object by hand and do the Bool.

The script runs till
bpy.context.object.modifiers["Boolean"].object = bpy.data.objects[NameWOFormat].

I understand that I have a problem with my selection. There is a small Modifier symbol next to the Name "Object1" in the Outliner Window. If it would run as it should, the symbol would be behind "Object1.001". That's the reason I think it's a selection problem.

Am I using the wrong command for the selection?

import bpy
import os
import bmesh
from pathlib import Path
from mathutils import Vector, kdtree, Matrix

NameWOFormat ="Object1"

# Modifier Boolean
def ModDif():
    global NameWoFormat
    global NameSubstrObject
    bpy.ops.object.mode_set(mode='OBJECT')
    bpy.ops.object.modifier_add(type='BOOLEAN')
    bpy.context.object.modifiers["Boolean"].operation = 'DIFFERENCE'
    bpy.context.object.modifiers["Boolean"].object = bpy.data.objects[NameWOFormat]
    bpy.ops.object.modifier_apply(apply_as='DATA', modifier="Boolean")

bpy.ops.import_scene.obj(C:/Object1.obj)

#===============================================================================
# Now I do some modifications on Object1. I save this block of code here.
#===============================================================================

# Change into Object-Mode
bpy.ops.object.mode_set(mode='OBJECT')

# Import Object1 again and use Boolean
bpy.ops.import_scene.obj(C:/Object1.obj)
NameSubstrObject = NameWOFormat + ".001"

# Do Boolean edit
bpy.ops.object.select_all(action='DESELECT')
bpy.data.objects[NameSubstrObject].select = True
ModDif()
You can add modifiers without using operators or relying on what is selected.

import bpy

# this creates Object1
bpy.ops.import_scene.obj(filepath='Object1.obj')
# this creates Object1.001
bpy.ops.import_scene.obj(filepath='Object1.obj')

obj = bpy.data.objects['Object1.001']
m = obj.modifiers.new(name='cutting modified obj',type='BOOLEAN')
m.object = bpy.data.objects['Object1']
m.operation = 'INTERSECT'