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/
#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/
# 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):

You receive error messages when you try to open an Office document, If you try to open a specific file in one of the Microsoft Office programs that If the filename or path is long, try renaming the file or copying it to a  TypeError: invalid file: When trying to make a file name a variable. Ask Question Asked 8 years, An invalid path was specified when tried to rename file. 0.

The below method is pretty verbose, because I'm using string operations instead of a regex. This hopefully makes it a bit more readable for you, but I'd suggest moving to a regex whenever you feel comfortable enough.

Please note, the function that deals with the string format to rename your scene will use a minimum of 2 digits (01, 02, etc) and a maximum of 3 digits (100, 101, etc). If you go above 999 iterations, you'll need to modify this slightly.

Note: This methodology relies on an underscore before your file version (eg. _01.mb) instead of your current string index method.

import maya.cmds as cmds

def getNextVersion():
    curName = cmds.file(query=True, expandName=True) # eg. D:/yourScene_01.mb
    curVersionFull = curName.split('_')[-1]          # eg. 01.mb
    versionExtension = curVersionFull.split('.')     # eg. ['01', 'mb']
    curVersionNum = int(versionExtension[0])         # eg. 1
    extension = versionExtension[1]                  # eg. 'mb'

    nextVersionNum = curVersionNum + 1               # increment your version
    if nextVersionNum < 100:
        nextVersionFull = '{:02d}.{}'.format(nextVersionNum, extension) # eg. 02.mb
        nextVersionFull = '{:03d}.{}'.format(nextVersionNum, extension) # eg. 100.mb

    newName = curName.replace(curVersionFull, nextVersionFull)
    return newName



You've already accepted another answer, and I believe the core of your issue is what @green-cell describes. As for how that is even possible, I don't actually know. Maya would generally not let you save to a folder that doesn't exist.


import maya.cmds as cmds
# Error: An invalid path was specified. : D:/doesntexist/
# Traceback (most recent call last):
#   File "<maya console>", line 2, in <module>
# RuntimeError: An invalid path was specified. : D:/doesntexist/ # 

Anyway, I've thrown together a more thorough function for you here. Please note that it's difficult to cater for all possible filename patterns, especially if users are allowed to specify their own file names in any part of the process. This time I'm using regular expressions, which makes your replacement much more robust (though, far from infallible).

import re
import os
import maya.cmds as cmds

def getNextVersion(createDir=True):
    '''Find next available filename iteration based on current scene name

        createDir (bool, optional): True to create the output directory if required. False to leave as-is (may trigger a failure)

        str|None: Full file path with incremented version number. None on failure

    # Grab current filename. This always returns something. If unsaved, it will return something unsavory, but still a string
    curFile = cmds.file(query=True, expandName=True)
    print('Current filename is {}'.format(curFile))

    # This matches a digit between 1 and 4 numbers in length, followed immediately by a file extension between 2 and 3 characters long
    m = re.match(r'(.+?)(\d{1,4})\.(\w{2,3})', curFile)
    if m == None:
        print('Failed at regex execution. Filename does not match our desired pattern')
        return None

    # Extract regex matches
    basePath =
    version =
    extension =

    # Failsafe. Should not trigger
    if not basePath or not version or not extension:
        print('Failed at failsafe. Filename does not match our desired pattern')
        return None

    # Increment file version
    numDigits = len(version)
    newFile = None
        version = int(version) + 1

        # Deal with padding
        newLength = len(str(version))
        if newLength > numDigits:
            numDigits = newLength

        # Compile new path
        newFile = '{base}{ver:{numDig:02d}d}.{ext}'.format(base=basePath, ver=version, numDig=numDigits, ext=extension)
    except Exception as e:
        print('Error parsing new version for path {}: {}'.format(curFile, e))
        return None

    # Another failsafe
    if not newFile:
        print('Failed at failsafe. Filename calculations succeeded, but new path is not valid')
        return None

    # Create output dir if needed
    dirname = os.path.dirname(newFile)
    if createDir and not os.path.isdir(dirname):
            print('Created all dirs required to build path {}'.format(dirname))
        except Exception as e:
            print('Error creating path {}: {}'.format(dirname, e))
            return None

    return newFile

nextVersion = getNextVersion()
if not nextVersion:
    cmds.error('Error parsing new filename increment. Please see console for more information')

Error message when you open or save a file in Microsoft Excel , If you are trying to open the file from your list of most recently used files on the File menu, make sure that the file has not been renamed, moved, or deleted. This error message occurs when you save or open a file if the path to the file (​including the file name) Make sure the specified folder exists. 3- Type “dir /x” to locate the DOS 8.3 short file name of the folder you want to poof; let’s pretend it’s called “Invalid Folder Version 7.0.1880 (x64)” and dir /x shows its short name to be “invali~1.188”

Updating #02:

I realized that the error happened only with the first version. Say if I have the first version as and try to version it up and save it, Maya will tell me that "An invalid path was specified". But if I rename it manually as and re-run the code again, the code will work normally.

It's not because of the number of the version though. Once I tried to save my first version as and try the script, it still gave me the same error. I had to rename it to manually and re-run the script, until then it worked.

Why can't I name a folder or file 'CON' in Windows?, absolute path to folder of choice, including drive letter]\[RESERVED_WORD] You can rename it without using any special software, just the command prompt: Source: The specified device name is invalid at Microsoft Docs. C:\NUL , but look at what happens when you try to access such a file or folder through Windows  "Invalid file name. The file name you specified could not be used. It may be the name of an existing file or directory, or you may not have permission to access the file." I have verified 14 hive log file and event viewer also.There is no relevant information about the issues.

How to force Windows to rename a file with a special character , File 31966 has been orphaned since all its filenames were invalid Windows will Try specifying the UNC path (see Naming Files, Paths, and Namespaces). Fixes a problem that occurs when you access a file share and then try to rename a file. Invalid device. Resolution. Hotfix information

Invalid path was specified. :(the path containing my project , Hi. For some reasons, I decided to change the name of the directory my maya file is in. Now when I try to save the file, it shows the error as  Make sure that the path of the file contains no more than the maximum number of characters. To do this, use one of the following methods. Rename the file so that it has a shorter name. Rename one or more folders that contain the file so that they have shorter names. Move the file to a folder that has a shorter path name.

How to Delete or Rename a Folder with an Invalid File Name in , How to Delete or Rename a Folder with an Invalid File Name in Windows 7, Vista​, XP, etc. One of my clients recently sent me a ZIP file with a bunch of songs he wanted to put on I keep on getting “the system cannot find the path specified”. The problem is your username contains an invalid character '.' in the path. You can file a bug report so we can fix this in the future as it should be ok on Linux to use a dot in the path. For now, use a path that does not contain a dot (.) It may also be possible to create the project from the command line and then open that project with the hub.

  • Updating: I've just tried to versioned up manually to fileName_02 (the first one was fileName_01) and the script ran. Anybody have any idea?
  • Thanks a lot Green Cell. The script ran now, but I'm still wondering how could this happen. I set a project from Maya project setup and for sure it did create a folder called assets where I can store every assets I got in there, and still, it told me the path isnt exist?
  • If you go to FIle>Set project it looks like it doesn't create the sub-directories, so I'm guessing that maybe it just didn't get created? Or you might want to double-check and print out the final path you're trying to save the new version to. Maybe it's accidentally pointing elsewhere.
  • Isnt it the D:/DATA/MAYA/myProject/assets/testFolder/ the final path I'm trying to save to? Because when I queried the expand name of the current file, which is var a in my codes, it returned D:/DATA/MAYA/myProject/assets/testFolder/ And I dont think I changed anything to the path, Maya just like suddenly didnt realize the path anymore :))
  • My guess is that testFolder didn't exist so it throws you that error.
  • It did exist in my drive actually. And the was in that as well. I just dont understand if Maya uses the path directly or understands it as something else and causes error for that?
  • Probably a good idea to throw getNextVersion() in a try-except clause, in case you're dealing with a scene name that does not conform to your template.
  • Hmm, thanks you so much for your way of approaching. It worked fine in some cases but not all unfortunately :( I still got the "An invalid path was specified" error when i run the script with *_01 file type (I mean the error happened only with the first version which is 01. If I saved the file as *_02 the error disappeared. If the first version was *_00 as once i tried, then I re-saved it as *_01 then it worked fine as well). Do you have any idea with this? Thank you for helping me out!!!
  • No worries. I've updated my answer now to illustrate use with regex, hopefully it makes sense. As for why you're failing occasionally on the first save, I really don't know, but I believe it has to do with the desired directory not existing like @green-cell mentions
  • To create regular expressions it can be useful to use a tool like
  • You're most welcome. Regex can be a bit confusing, and I'm far from a veteran at it. Use the site I linked to above, it will explain your expressions to you as you type them, plus provide you with a cheat sheet for common operators