diff --git a/pyutil.py b/pyutil.py index f9ae532..9046b5a 100644 --- a/pyutil.py +++ b/pyutil.py @@ -87,22 +87,54 @@ def file_exists(filePath): else: return False -def file_rename(filename, fromfile): +# @def Função para renomear arquivo de video gerado pelo blender +# @see entrada: /temp/arquivo_video_0001-0250.mp4 +# @see saida: /temp/arquivo_video.mp4 +# @param string fileFullPath: Caminho do arquivo a ser renomeado +# @param bool useTimeStamp: Renomeia o arquivo de acordo com a data e hora do sistema +# @param bool overwrite: Sobreescreve o arquivo +# @return string Retorna o nome do arquivo renomeado +def file_rename(fileFullPath, useTimeStamp = False, overwrite = True): from shutil import move - newFilename = "" - isValidChar = True + from os.path import abspath, basename, dirname, join, splitext + if (file_exists(fileFullPath) == False): + return "" + filePath = dirname(abspath(fileFullPath)) + filename = basename(splitext(fileFullPath)[0]) + extension = splitext(fileFullPath)[1] + filenameInv = "" + isValidChar = False + + # Percorre o "filename" do final para o inicio copiando caracteres após o primeiro '_' encontrado for char in reversed(filename): if (isValidChar == True): - newFilename += char + filenameInv += char if (char == '_'): isValidChar = True - elif (char == '.'): - isValidChar = False - if (len(filename) != len(newFilename)): - try: - move(filename, newFilename[::-1]) - return 1 - except Exception as e: - printStackTrace(fromfile) - return 0 - return 0 + try: + + # Inverte sequencia de caracteres que foi copiada + filenameInv = filenameInv[::-1] + + if (useTimeStamp == True): + # Recupera novo fullPath + nome do arquivo + data/hora + extensão + newFilename = join(filePath, "%s_%s%s" % (filenameInv, getTimeStamp(), extension)) + else: + # Recupera novo fullPath + nome do arquivo + extensão + newFilename = join(filePath, "%s%s" % (filenameInv, extension)) + + # Enumera o nome do arquivo caso o parametro "overwrite" seja "False" e o arquivo já exista + if (overwrite == False): + count = 0 + while (file_exists(newFilename) == True): + count += 1 + # newFilename = join(filePath, "%s_%i%s" % (filenameInv, count, extension)) + newFilename = join(filePath, "%s_%0.4i%s" % (filenameInv, count, extension)) + + log("Rename: '%s' to: '%s'" %(fileFullPath, newFilename)) + move(fileFullPath, newFilename) + return newFilename + + except Exception as e: + printStackTrace(__file__) + return "" -- libgit2 0.21.2