2
$\begingroup$

I created a script that runs on an individual file, but I want to automate it to run on a long list of files. Essentially, I want to automate this:

  1. Import file from list
  2. Various script steps
  3. Export to new file
  4. Clear current scene/model/data/objects/etc (presumably through opening the startup .blend file which I have removed all items from)
  5. Loop to next file on list

Import/export instead of open/save because file is in a non-native blender format.

Any direction would be appreciated, as I am still relatively new to Blender and Python.

$\endgroup$

1 Answer 1

1
$\begingroup$

Something like that should work. I assume you want to import gltf but you can swap the importer and extension quite easily.

from pathlib import Path
import bpy

model_filepaths = [f for f in Path(r"D:\path\to\your\folder").glob('**/*.gltf') if f.is_file()]

for filepath in model_filepaths:
    # Create a brand new file
    bpy.ops.wm.read_homefile()
    # Import model
    bpy.ops.import_scene.gltf(filepath=str(filepath))
    # Do something
    for obj in bpy.data.objects:
        print(obj.name)
    # Save file
    bpy.ops.wm.save_as_mainfile(filepath=str(filepath.with_suffix(".blend")))
$\endgroup$
4
  • $\begingroup$ In testing out bpy.ops.wm.read_homefile, it causes the import to fail and errors out. Snippet of error message: if bpy.context.object and bpy.context.object.type == 'ARMATURE': AttributeError: 'Context' object has no attribute 'object' $\endgroup$
    – MikeSmo
    Dec 2, 2023 at 20:32
  • $\begingroup$ Please post your script, these lines are not part of my answer $\endgroup$
    – Gorgious
    Dec 3, 2023 at 11:50
  • $\begingroup$ Just added the test code in my post above. The issue looks to be that bpy.ops.wm.read_homefile() clears context to None (for example, bpy.context.window, etc.) $\endgroup$
    – MikeSmo
    Dec 7, 2023 at 0:53
  • $\begingroup$ Yup, I suggest adding a small delay with an application timer so the context initializes. docs.blender.org/api/current/bpy.app.timers.html You can also try purging everything in the file instead of loading a brand new one but there might be leftover data and it will take more time $\endgroup$
    – Gorgious
    Dec 7, 2023 at 8:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .