Search code examples
pythonfilerenamemaya

An invalid path was specified when tried to rename file


I'm writing a version-up script (an auto-version-number-incrementing script) in Python, but I'm feeling like I'm having a weird thing going on with my renaming code in Maya.

I'm not sure how Maya stored the file path but whenever I tried to rename it, it told me that "An invalid path was specified." along with my file path.

And to make things odder I guess, it only said this error in a couple of cases. Once I tried to rename a file from Maya's asset folder (yes I already set project for Maya to look for), it gave me that error. But everything worked fine when I opened files from Maya's scene folder. And then, in another project folder, everything worked just perfectly no matter if I opened a asset file or a scene file.

Anybody have any idea what's going on? Thank you very much!!!

a = cmds.file (query = True, expandName = True)  #result: D:/DATA/MAYA/myProject/assets/testFolder/test_01.ma
#print a[:-3]
x,y = a[-5:-3]  #result: x = 0, y = 1
x = int(x)      
y = int(y)
if y < 9:
    y += 1      #result: x = 0, y = 2
    #print (y)
elif y == 9:
    y = 0 
    x += 1      
x = str(x)
y = str(y)
b = a.replace(a[-5:-3], x+y)  #replace 01 with 02
#print b
cmds.file (rename = b)  #this is where I got the error. the result should be D:/DATA/MAYA/myProject/assets/testFolder/test_02.ma

Solution

  • # Error: RuntimeError: file <maya console> line 1: An invalid path was specified.
    

    This error triggers when running cmds.file(rename=your_path) but the directory of the path that's supplied doesn't exist, which makes sense because it isn't valid!

    So all you have to do is create the folder before calling it. You can use os.makedirs for that. You don't want to include the file name in the full path, so you can also use os.path.dirname to strip it out. So instead of passing it "/my/full/path/file_name.mb", using os.path.dirname will strip it to "/my/full/path".

    So expanding on itypewithmyhands's answer it will look like this:

    import os
    
    newVersion = getNextVersion()
    versionFolder = os.path.dirname(newVersion)
    if not os.path.exists(versionFolder):
        os.makedirs(versionFolder)