0
$\begingroup$

I need help adding an .obj file via scripting. I've tried using this line of code, but I'm having issues importing the obj file:

bpy.ops.import_scene.obj(filepath="./example.obj")

I think the problem is how I define the file path, but I don't know how to fix it.

$\endgroup$
  • 2
    $\begingroup$ To make the path relative to the blender file use path = "//fileinsamefolderasblend.obj" $\endgroup$ – batFINGER Apr 6 at 16:24
  • $\begingroup$ @batFINGER Can I specify a path relative to the script (not the blend file)? $\endgroup$ – VortexHero Apr 6 at 16:57
  • 1
    $\begingroup$ stackoverflow.com/… $\endgroup$ – batFINGER Apr 6 at 17:05
  • $\begingroup$ @batFINGER dir = os.path.dirname(__file__) (newline) file = os.path.join(dir, 'example.obj') (newline) bpy.ops.import_scene.obj(filepath=file) I tried this (from the search) and it also doesn't work. I have os imported. $\endgroup$ – VortexHero Apr 6 at 17:29
  • 1
    $\begingroup$ Where, what is the script, how are you running it? If blend file is saved use as commented above to get path relative to blend file. . If not saved then reverts to "." which is the folder from where blender is run. eg if start blender from console from desktop folder this is where. If you are running from program icon, possibly your install folder. Recommend using pathlib import pathlib; print(pathlib.Path.cwd()). If the script is imported as an addon then __dir__ above will work as expected. If you are running script from main thread via text editor ...? $\endgroup$ – batFINGER Apr 7 at 4:07
0
$\begingroup$
import bpy
file_loc = 'C:\Models\Model.obj'
imported_object = bpy.ops.import_scene.obj(filepath=file_loc)
obj_object = bpy.context.selected_objects[0]
print('Imported name: ', obj_object.name)

Result

| improve this answer | |
$\endgroup$
  • 1
    $\begingroup$ How would I grab a .obj in the same folder as the script? (aka a relative path) $\endgroup$ – VortexHero Apr 6 at 18:08
  • $\begingroup$ If you run it inside blender, I think it uses blender’s location, and you have to put a path in here, but I am not sure $\endgroup$ – cxnt Apr 6 at 21:27
0
$\begingroup$

You simply need to combine your relative path with the current directory, which you can get using the os library:

import os
bpy.ops.import_scene.obj(filepath=os.getcwd()+"/example.obj")
| improve this answer | |
$\endgroup$
  • $\begingroup$ I recommend using os.path.join() to be on the safe side... $\endgroup$ – brockmann Apr 8 at 12:58

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.