I'm new on Blender and I'm struggling with Blender's import operator for STL files. In my code, I try to load a file from the browser and then make some actions on the loaded object. I can get the file I want but the code continues to run before the STL file is loaded, so I get the error: KeyError: 'bpy_prop_collection[key]: key "file_name" not found'

Here's my code:

import bpy
from bpy_extras.io_utils import ImportHelper
from bpy_extras.io_utils import ExportHelper
from bpy.props import StringProperty, BoolProperty, EnumProperty
from bpy.types import Operator

#clearing previous objects

#stl file loading

#some action with the file
x_dimension = bpy.data.objects["file_object"].dimensions[0]

Using :

class ImportSomeData(Operator, ImportHelper):
   """This appears in the tooltip of the operator and in the generated docs"""
   bl_idname = "import_test.some_data"
   bl_label = "Import Some Stl File"
   bl_options = {'REGISTER', 'UNDO'}

   # ImportHelper mixin class uses this
   filename_ext = ".stl"
   filter_glob: bpy.props.StringProperty(
   def execute(self, context):
       if self.filepath:
           # Print the imported object reference
           print ("Imported object:", context.object)
           # Create a material
           mat = bpy.data.materials.new(name="STLMaterial")
           # Append the material to the last slot

       return {'FINISHED'}
# Only needed if you want to add into a dynamic menu
def menu_func_import(self, context):
   self.layout.operator(ImportSomeData.bl_idname, text="Text Import Operator")

def register():

def unregister():

if __name__ == "__main__":

Found on How to import a STL file using the file browser?.

Is there a way to stop the code until the STL file has loaded?


  • $\begingroup$ I guess this is a logic error caused by removing the selected object. Suggest store a pointer or at least the name and try to remove the object based on that. What's your goal? Import the object, render, remove? Can you provide a model to test? Related: Import multiple STL files and modify the incoming objects in one go? $\endgroup$
    – brockmann
    May 29 at 18:40
  • $\begingroup$ I bypassed the problem by adding my actions in the "execute" section of the code and it works. But thanks for the answer! $\endgroup$ Jun 3 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.