尝试重命名文件时指定了无效路径

我正在用 Python 编写版本升级脚本(自动版本号递增脚本),但我感觉在 Maya 中重命名代码时发生了奇怪的事情。


我不确定 Maya 是如何存储文件路径的,但每当我尝试重命名它时,它都会告诉我“指定了无效路径”。连同我的文件路径。


为了让事情变得更奇怪,我猜它只在几个情况下说这个错误。一旦我尝试从 Maya 的资产文件夹中重命名文件(是的,我已经为 Maya 设置了要查找的项目),它给了我这个错误。但是当我从 Maya 的场景文件夹中打开文件时,一切正常。然后,在另一个项目文件夹中,无论我打开资产文件还是场景文件,一切都运行良好。


有人知道发生了什么吗?非常感谢!!!


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


缥缈止盈
浏览 261回答 3
3回答

不负相思意

# Error: RuntimeError: file <maya console> line 1: An invalid path was specified.运行时会触发此错误,cmds.file(rename=your_path)但提供的路径的目录不存在,这是有道理的,因为它无效!所以你所要做的就是在调用它之前创建文件夹。你可以使用os.makedirs它。您不想在完整路径中包含文件名,因此您也可以使用os.path.dirname将其剥离。所以不是传递它"/my/full/path/file_name.mb",而是使用os.path.dirname将它剥离到"/my/full/path".因此,扩展 itypewithmyhands 的答案将如下所示:import osnewVersion = getNextVersion()versionFolder = os.path.dirname(newVersion)if not os.path.exists(versionFolder):&nbsp; &nbsp; os.makedirs(versionFolder)

慕码人8056858

下面的方法非常冗长,因为我使用的是字符串操作而不是正则表达式。这希望它对你来说更具可读性,但我建议只要你觉得足够舒服就改用正则表达式。请注意,处理字符串格式以重命名场景的函数将使用最少 2 位数字(01、02 等)和最多 3 位数字(100、101 等)。如果超过 999 次迭代,则需要稍作修改。注意: 此方法依赖于文件版本之前的下划线(例如 _01.mb),而不是当前的字符串索引方法。import maya.cmds as cmdsdef getNextVersion():&nbsp; &nbsp; curName = cmds.file(query=True, expandName=True) # eg. D:/yourScene_01.mb&nbsp; &nbsp; curVersionFull = curName.split('_')[-1]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # eg. 01.mb&nbsp; &nbsp; versionExtension = curVersionFull.split('.')&nbsp; &nbsp; &nbsp;# eg. ['01', 'mb']&nbsp; &nbsp; curVersionNum = int(versionExtension[0])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# eg. 1&nbsp; &nbsp; extension = versionExtension[1]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # eg. 'mb'&nbsp; &nbsp; nextVersionNum = curVersionNum + 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# increment your version&nbsp; &nbsp; if nextVersionNum < 100:&nbsp; &nbsp; &nbsp; &nbsp; nextVersionFull = '{:02d}.{}'.format(nextVersionNum, extension) # eg. 02.mb&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; nextVersionFull = '{:03d}.{}'.format(nextVersionNum, extension) # eg. 100.mb&nbsp; &nbsp; newName = curName.replace(curVersionFull, nextVersionFull)&nbsp; &nbsp; return newNamecmds.file(rename=getNextVersion())cmds.file(save=True)更新:您已经接受了另一个答案,我相信您问题的核心是@green-cell 所描述的。至于这怎么可能,我真的不知道。Maya 通常不会让您保存到不存在的文件夹中。例如:import maya.cmds as cmdscmds.file(rename="D:/doesntexist/somefile.mb")# Error: An invalid path was specified. : D:/doesntexist/# Traceback (most recent call last):#&nbsp; &nbsp;File "<maya console>", line 2, in <module># RuntimeError: An invalid path was specified. : D:/doesntexist/ #&nbsp;无论如何,我在这里为您整理了一个更全面的功能。请注意,很难满足所有可能的文件名模式,特别是如果允许用户在过程的任何部分指定自己的文件名。这次我使用regular expressions,这使您的替换更加健壮(尽管远非万无一失)。import reimport osimport maya.cmds as cmdsdef getNextVersion(createDir=True):&nbsp; &nbsp; '''Find next available filename iteration based on current scene name&nbsp; &nbsp; Args:&nbsp; &nbsp; &nbsp; &nbsp; createDir (bool, optional): True to create the output directory if required. False to leave as-is (may trigger a failure)&nbsp; &nbsp; Returns:&nbsp; &nbsp; &nbsp; &nbsp; str|None: Full file path with incremented version number. None on failure&nbsp; &nbsp; '''&nbsp; &nbsp; # Grab current filename. This always returns something. If unsaved, it will return something unsavory, but still a string&nbsp; &nbsp; curFile = cmds.file(query=True, expandName=True)&nbsp; &nbsp; print('Current filename is {}'.format(curFile))&nbsp; &nbsp; # This matches a digit between 1 and 4 numbers in length, followed immediately by a file extension between 2 and 3 characters long&nbsp; &nbsp; m = re.match(r'(.+?)(\d{1,4})\.(\w{2,3})', curFile)&nbsp; &nbsp; if m == None:&nbsp; &nbsp; &nbsp; &nbsp; print('Failed at regex execution. Filename does not match our desired pattern')&nbsp; &nbsp; &nbsp; &nbsp; return None&nbsp; &nbsp; # Extract regex matches&nbsp; &nbsp; basePath = m.group(1)&nbsp; &nbsp; version = m.group(2)&nbsp; &nbsp; extension = m.group(3)&nbsp; &nbsp; # Failsafe. Should not trigger&nbsp; &nbsp; if not basePath or not version or not extension:&nbsp; &nbsp; &nbsp; &nbsp; print('Failed at failsafe. Filename does not match our desired pattern')&nbsp; &nbsp; &nbsp; &nbsp; return None&nbsp; &nbsp; # Increment file version&nbsp; &nbsp; numDigits = len(version)&nbsp; &nbsp; newFile = None&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; version = int(version) + 1&nbsp; &nbsp; &nbsp; &nbsp; # Deal with padding&nbsp; &nbsp; &nbsp; &nbsp; newLength = len(str(version))&nbsp; &nbsp; &nbsp; &nbsp; if newLength > numDigits:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; numDigits = newLength&nbsp; &nbsp; &nbsp; &nbsp; # Compile new path&nbsp; &nbsp; &nbsp; &nbsp; newFile = '{base}{ver:{numDig:02d}d}.{ext}'.format(base=basePath, ver=version, numDig=numDigits, ext=extension)&nbsp; &nbsp; except Exception as e:&nbsp; &nbsp; &nbsp; &nbsp; print('Error parsing new version for path {}: {}'.format(curFile, e))&nbsp; &nbsp; &nbsp; &nbsp; return None&nbsp; &nbsp; # Another failsafe&nbsp; &nbsp; if not newFile:&nbsp; &nbsp; &nbsp; &nbsp; print('Failed at failsafe. Filename calculations succeeded, but new path is not valid')&nbsp; &nbsp; &nbsp; &nbsp; return None&nbsp; &nbsp; # Create output dir if needed&nbsp; &nbsp; dirname = os.path.dirname(newFile)&nbsp; &nbsp; if createDir and not os.path.isdir(dirname):&nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; os.makedirs(dirname)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print('Created all dirs required to build path {}'.format(dirname))&nbsp; &nbsp; &nbsp; &nbsp; except Exception as e:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print('Error creating path {}: {}'.format(dirname, e))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return None&nbsp; &nbsp; return newFilenextVersion = getNextVersion()if not nextVersion:&nbsp; &nbsp; cmds.error('Error parsing new filename increment. Please see console for more information')else:&nbsp; &nbsp; cmds.file(rename=nextVersion)&nbsp; &nbsp; cmds.file(save=True)

智慧大石

更新#02:我意识到错误只发生在第一个版本中。假设我有第一个版本为 sceneName_01.ma 并尝试对其进行版本升级并保存,Maya 会告诉我“指定了无效路径”。但是如果我手动将其重命名为sceneName_02.ma并再次重新运行代码,代码将正常工作。这不是因为版本的数量。一旦我尝试将我的第一个版本保存为 sceneName_00.ma 并尝试脚本,它仍然给了我同样的错误。我不得不手动将其重命名为 sceneName_01.ma 并重新运行脚本,直到它工作为止。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python