Search code examples
pythonimportreferencerenamemaya

Name of object on import


I'm having trouble getting the name of the reference object (to rename it) importing a number of objects into Maya with Python:

import maya.cmds as cmds
import os

myFolder = r"D:\temp\objs"
objFiles = cmds.getFileList(folder = myFolder, filespec = "*.%s" % "OBJ")
for item in objFiles:
  fname = os.path.join(myFolder, item)
  x = cmds.file(fname, i = True) 

Turns out x is the pathname of the object and not the name of object as displayed in the outliner.

What's the correct reference in order to rename it?


Solution

  • The code you posted is just doing the imports. You're looking to find the objects you have imported at each step of the loop?

    The easy way to isolate imported objects is to specify a namespace when you import. You can then use the new namespace to quickly spot objects:

    for eachfile in list_of_files:
        # make a namespace.  In production you might want to double
        # check to make sure the same namespace does not already exist
        import_ns = os.path.splitex(os.path.basename(eachfile))[0]  
        cmds.file(eachfile, i=True, ns = import_ns)
    
        # this gets all of the imported stuff:
        imported_objects = cmds.ls (import_ns + ":*") 
    
        # now you can loop over it and rename as needed.
    

    You can pick only some classes of objects out of imported_objects by adding a second call to ls with the type flag, ie

        imported_shapes = cmds.ls(imported_objects, type='shape')