13

In my export script I wish to export all object named 'foo*' in one format, and all objects named 'bar*' in another format.

I could write 2 separate exporters that operate on the selection (so I select all 'foo*' objects and execute FooExporter, rinse and repeat for 'bar*'

But I would rather get it done in one go, with:

fooList = get_objects_starting( 'foo' )
for obj in fooList:
    foo_exporter( obj )

barList = get_objects_starting( 'bar' )
for obj in barList:
    bar_exporter( obj )

How can I get a list of all 'foo*' objects?

stacker
  • 38,549
  • 31
  • 141
  • 243
P i
  • 3,921
  • 9
  • 34
  • 53

2 Answers2

18

If you want to use shell style globbing (*.foo, *.*abc, [ab]*.bar) (as is used in the question), you can use fnmatch, either fnmatch.fnmatchcase or fnmatch.fnmatch for case insensitive matches.

import bpy
import fnmatch

scene = bpy.context.scene

foo_objs = [obj for obj in scene.objects if fnmatch.fnmatchcase(obj.name, "foo*")]

Otherwise you can simply do...

foo_objs = [obj for obj in scene.objects if obj.name.startswith("foo")]

For more powerful pattern matching: check on Python's built-in regular expression (re module)

ideasman42
  • 47,387
  • 10
  • 141
  • 223
9

Just combine list comprehension with str.startswith:

import bpy

foo_objs = [obj for obj in bpy.data.objects if obj.name.startswith("foo")]
p2or
  • 15,860
  • 10
  • 83
  • 143
Adhi
  • 14,310
  • 1
  • 55
  • 62
  • 3
    Since the question mentions use for an exporter, bpy.data.objects will give all objects from all scenes. Which you probably wont want, best use scene.objects – ideasman42 Jan 10 '14 at 06:39