insert gaps in numbering of files in folder Args: folderPath (str): path to folder to search prefix (str): prefix of files to insert gap index (int): where to insert the gap Returns: None
(folderPath, prefix, index)
| 54 | |
| 55 | |
| 56 | def insertGaps(folderPath, prefix, index): |
| 57 | """insert gaps in numbering of files in folder |
| 58 | Args: |
| 59 | folderPath (str): path to folder to search |
| 60 | prefix (str): prefix of files to insert gap |
| 61 | index (int): where to insert the gap |
| 62 | Returns: |
| 63 | None |
| 64 | """ |
| 65 | |
| 66 | fileList = getFilesWithPrefix(folderPath, prefix) # files sorted ascending order |
| 67 | fileRegex = re.compile(prefix + "(\d{1,})(.\w+)") |
| 68 | |
| 69 | max_length = len( |
| 70 | fileRegex.search(fileList[-1]).group(1) |
| 71 | ) # max length of largest number, for padding zeros |
| 72 | |
| 73 | firstIndex = int(fileRegex.search(fileList[0]).group(1)) # smallest number |
| 74 | lastIndex = int(fileRegex.search(fileList[-1]).group(1)) # largest number |
| 75 | |
| 76 | if index >= firstIndex and index <= lastIndex: # if gap index falls in range |
| 77 | |
| 78 | i = 0 |
| 79 | currIndex = firstIndex |
| 80 | while currIndex < index: |
| 81 | # loop till the file number is >= gap index |
| 82 | i += 1 |
| 83 | currIndex = int(fileRegex.search(fileList[i]).group(1)) |
| 84 | |
| 85 | if currIndex == index: # if gap index is taken, make a gap else already free |
| 86 | |
| 87 | for file in fileList[i:][::-1]: |
| 88 | # loop through reversed file list, to prevent overwriting results and increment file number |
| 89 | |
| 90 | mo = fileRegex.search(file) |
| 91 | newFileNum = int(mo.group(1)) + 1 |
| 92 | newFileName = ( |
| 93 | prefix |
| 94 | + "0" * (max_length - len(str(newFileNum))) |
| 95 | + str(newFileNum) |
| 96 | + mo.group(2) |
| 97 | ) |
| 98 | shutil.move(os.path.abspath(file), os.path.abspath(newFileName)) |
| 99 | |
| 100 | |
| 101 | if __name__ == "__main__": |
nothing calls this directly
no test coverage detected