in python load blender file & delete objects I have a python file I am using in blender to load up an old file another script saved previously using save_as_mainfile(). I want to delete some objects from the scene, but for the purpose of this question I will try to delete them all. Here is the code.

bpy.ops.wm.open_mainfile(filepath=filename)
bpy.ops.object.select_all(action='DESELECT')
for ob in bpy.data.objects:
    ob.select = True
result = bpy.ops.object.delete()
print("{} objects remain because results={}".format(len(bpy.data.objects), result))


The result of running this is "35 objects remain because results={'CANCELLED'}" .. I do not know why the operation was cancelled, and I am hoping the len is 0. I have checked and I am in OBJECT mode (indeed trying to change modes gave me a poll error of some kind).

Thanks.
Instead of looping on all object you can do this:

bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)


If you want to delete some specific objects you can use the below script. I had a .blend file (provided below) which has three cubes Cube Cube.001 and Cube.002, in this script I deleted both Cube and Cube.001 where Cube.002 is not deleted.

import bpy

C = bpy.context
scene = C.scene
bpy.ops.object.select_all(action='DESELECT')
for ob in bpy.data.objects:
    if ob.name in ['Cube','Cube.001']:
        ob.select = True
        scene.objects.active = ob
bpy.ops.object.delete(use_global=False)


.blend file can be found here: