Blender Python: How to import(append) material by bpy script

Basic:

bpy.ops.wm.append(filename, directory)” imports material and other assets from an blend file. It is the same process as you can do in UI with “File > Append”.

But the rule of the function’s input — filename and directory — is a little bit tricky.

directory:

directory must be a string which contains path of the blend file, name of blend file, and category name.
The structure of string is shown below.

directory = “<path>/<blend file name>\\<category>\\”

Take care to use backslash for separator of category.

filename:

File name should be a material name in the blend file.

filename = “<material name>”

 

Simple example:

If you want to import “test_material1” from “test1.blend” inĀ “/Users/SOMEONE/Desktop/import-material_test/”, the code is this.

import bpy

path = "/Users/SOMEONE/Desktop/import-material_test/test1.blend\\Material\\"
material_name = "test_material1"
bpy.ops.wm.append(filename=material_name, directory=path)

tutorial_import-material_screenshot1

 

Importing material with addon script:

When you want to import material in Blender addon, you can ship a blend file with addon code.
The folder structure below shows an example. With addon script code, there is a blend file in “materials” folder.

tutorial_import-material_folder1

 

To import material in addon, you should get path of the addon folder.
“os.path.dirname(__file__)” can get path of addon folder. So you cam use the function for file path.

An example code is this.

import bpy
import os

path = os.path.dirname(__file__) + "/materials/materials1.blend\\Material\\"
material_name = "test_material1"
bpy.ops.wm.append(filename=material_name, directory=path)

I used the similar code for “Crack It” Addon.

Leave a Reply