Featured post

new redirect for blender.org bpy docs.

http://www.blender.org/api/blender_python_api_current/ As of 10/11 november 2015 we can now link to the current api docs and not be worr...

March 20, 2012

importing .obj

'''
>>> bpy.ops.import_scene.obj(
obj()
bpy.ops.import_scene.obj(filepath="", filter_glob="*.obj;*.mtl", use_ngons=True, use_edges=True, use_smooth_groups=True, use_split_objects=True, use_split_groups=True, use_groups_as_vgroups=False, use_image_search=True, split_mode='ON', global_clamp_size=0, axis_forward='-Z', axis_up='Y')
'''
import bpy
full_path_to_file = "C:\\Users\\dealga\\Documents\\OBJECTS\\obj_1.obj"
bpy.ops.import_scene.obj(filepath=full_path_to_file)
view raw import_part1.py hosted with ❤ by GitHub
The separator used here is '\\', but this varies from OS to OS. Python has a module called os to take some of the headache away.
import os
full_path_to_directory = os.path.join('C:\\', 'Users', 'name', 'Documents', 'OBJECTS')
full_path_to_file = os.path.join(full_path_to_directory, "obj_1.obj")
print(full_path_to_directory)
print(full_path_to_file)
view raw import_part2.py hosted with ❤ by GitHub
The above code allows you to do this stuff manually, research and experiment with the os module, it's great to understand how it works.

You could write a plugin using the directory selector built into Blender, so that you can navigate to a directory and obtain the string full_path_to_directory that way, but that's a different topic.

Blog reader pmpfx wondered how this syntax was glued together, so I think the above should clarify the path issues. The following snippet uses the os module to list the content of a directory. It will gather all files that are .obj and import them. No error checking is done, the path has to be valid. Conveniently the os module provides ways to check if a path is valid, read the docs.
import os
import bpy
full_path_to_directory = os.path.join('C:\\', 'Users', 'name', 'Documents', 'OBJECTS')
# get list of all files in directory
file_list = os.listdir(full_path_to_directory)
# reduce the list to files ending in 'obj'
# using 'list comprehensions'
obj_list = [item for item in file_list if item[-3:] == 'obj']
# loop through the strings in obj_list.
for item in obj_list:
full_path_to_file = os.path.join(full_path_to_directory, item)
bpy.ops.import_scene.obj(filepath=full_path_to_file)
view raw import_part3.py hosted with ❤ by GitHub
Here's a description of how to sanitize a blend