-
Notifications
You must be signed in to change notification settings - Fork 0
/
ch10_gaps_insert.py
56 lines (37 loc) · 1.56 KB
/
ch10_gaps_insert.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
### Project: Insert gaps into numbered files
# this program insert gaps into numbered giles so that a new file can be added.
# (assuming files are already ordered by "Filling in the Gaps" program)
# ex. gapping #3, in spam002.txt, spam003.txt. spam004.txt
# becomes spam002.txt, spam004.txt. spam005.txt
import re, os, shutil
from pathlib import Path
#searches for files with spam prefix
prefixRegex = re.compile(r'(^spam)(0*)(\d+)(.[a-zA-Z]+)*')
def skipFiles(folder, filetoSkip):
print(f'Creating gap at postion: {filetoSkip}\n')
folder = Path(folder)
matchedlist = []
for match in os.listdir(folder):
mo = prefixRegex.search(match)
if mo == None:
continue
newnamePath = Path(folder, match)
matchedlist.append(newnamePath.name)
firstcount = int()
count = int()
filetoSkip = filetoSkip - 1
for match in sorted(matchedlist, reverse = True):
mo = prefixRegex.search(match)
if int(mo.group(3)) == filetoSkip:
break
count = int(mo.group(3)) + 1
numstr = (''.join(mo.group(2) + str(count)))
while len(numstr) > 3:
numstr = numstr[1:]
newfilename = mo.group(1) + numstr + mo.group(4)
print(f'Renaming {match} to {newfilename}')
oldnamePath = Path(folder, match)
newnamePath = Path(folder, newfilename)
shutil.move(oldnamePath, newnamePath)
print('\nGap creation complete.')
skipFiles('absolute path of directory', 4)