|
| 1 | +""" |
| 2 | +fillGap.py - A program that finds all files with a given prefix, |
| 3 | +such as spam001.txt, spam002.txt, and so on, in a single folder |
| 4 | +and locates any gaps in the numbering (such as if there is a |
| 5 | +spam001.txt and spam003.txt but no spam002.txt) and reanames all the |
| 6 | +files to close this gap. |
| 7 | +
|
| 8 | +Usage: run "python3 fillGap.py" and Enter the file prefix, estension |
| 9 | +and taret folder in the prompt that appears. The files would be named |
| 10 | +in order, closing gaps, if any. |
| 11 | +""" |
| 12 | + |
| 13 | +import os |
| 14 | +import sys |
| 15 | +import re |
| 16 | +from math import log |
| 17 | +import shutil |
| 18 | + |
| 19 | +# Input file/folder name and extension |
| 20 | +filename = input("Enter the name prefix for the files/folders\n") |
| 21 | +print("\nEnter the extension after the dot in filenames (like txt in spam01.txt)") |
| 22 | +print("Type \"folder\" (without the quotes) if the files are folders") |
| 23 | +ext = input() |
| 24 | + |
| 25 | +# Create filename regex |
| 26 | +if ext == 'folder': |
| 27 | + nameSeq = re.compile( |
| 28 | + r'^' + re.escape(filename) + r'\d*' + r'$' |
| 29 | + ) |
| 30 | +else: |
| 31 | + nameSeq = re.compile( |
| 32 | + r'^' + re.escape(filename) + r'\d*' + |
| 33 | + r'[.]' + re.escape(ext) + r'$' |
| 34 | + ) |
| 35 | + |
| 36 | +# Put matching file/folder names in a list |
| 37 | +path = input("\nEnter the path of folder containing the file/folder\n") |
| 38 | +path = os.path.abspath(path) |
| 39 | +print(path) |
| 40 | +if not os.path.isdir(path): |
| 41 | + print("The path entered is not a valid folder.") |
| 42 | + sys.exit() |
| 43 | +else: |
| 44 | + lst = [] |
| 45 | + for entry in os.listdir(path): |
| 46 | + found = nameSeq.search(entry) |
| 47 | + if found: |
| 48 | + lst.append(found[0]) |
| 49 | + |
| 50 | +# Sort list and take size of list as padding |
| 51 | +lst = sorted(lst) |
| 52 | +padding = int(log(len(lst))//log(10)) + 1 |
| 53 | + |
| 54 | +# Rename files/folders |
| 55 | +for i in range(len(lst)): |
| 56 | + if ext == 'folder': |
| 57 | + newName = filename + str(i).rjust(padding, '0') |
| 58 | + oldPath = os.path.join(path, lst[i]) |
| 59 | + newPath = os.path.join(path, newName) |
| 60 | + shutil.move(oldPath, newPath) |
| 61 | + else: |
| 62 | + newName = filename + str(i).rjust(padding, '0') + '.' + ext |
| 63 | + oldPath = os.path.join(path, lst[i]) |
| 64 | + newPath = os.path.join(path, newName) |
| 65 | + shutil.move(oldPath, newPath) |
| 66 | +print("The files are renamed with gaps closed.") |
0 commit comments