I have a lot of images in subdirectories with same string in filename and I want to rename these files and append a suffix to their names.
Example:
JavaScript
x
10
10
1
1/AB2011-BLUE-BW.jpg
2
1/AB2011-WHITE-BW.jpg
3
1/AB2011-BEIGE-BW.jpg
4
2/AB2011-WHITE-2-BW.jpg
5
2/AB2011-BEIGE-2-BW.jpg
6
1/AB2012-BLUE-BW.jpg
7
1/AB2012-WHITE-BW.jpg
8
1/AB2012-BEIGE-BW.jpg
9
10
I want to rename this files in
JavaScript
1
10
10
1
1/AB2011-01.jpg
2
1/AB2011-02.jpg
3
1/AB2011-03.jpg
4
2/AB2011-04.jpg
5
2/AB2011-05.jpg
6
1/AB2012-01.jpg
7
1/AB2012-02.jpg
8
1/AB2012-03.jpg
9
10
How can I do this in bash or python? Which image get 01,02,03 doesn’t matter.
Advertisement
Answer
Hopefully I understood what you wanted correctly. But heres how to do it below.
JavaScript
1
43
43
1
# importing os module
2
import os
3
4
# Function to rename multiple files
5
def main():
6
7
folder = "1"
8
9
# Keeps track of count of file name based on first field
10
fileNameCountDic = {}
11
12
for count, filename in enumerate(os.listdir(folder)):
13
14
# Original path to file
15
src = f"{folder}/{filename}" # foldername/filename, if .py file is outside folder
16
17
# Get first field in file name so "B2011-BLUE-BW.jpg" -> "B2011"
18
firstFileNameField = filename.split("-")[0]
19
20
# If first field in filename is not in dic set it to be the first one
21
if firstFileNameField not in fileNameCountDic:
22
fileNameCountDic[firstFileNameField]=1
23
else: # Else inc the count
24
fileNameCountDic[firstFileNameField]+=1
25
26
# Turn file count number to String
27
fileNumber = str(fileNameCountDic[firstFileNameField])
28
if len(fileNumber)==1: # Add space if one digit
29
fileNumber=" "+fileNumber
30
31
# Set the new path of the file
32
dst = f"{folder}/{firstFileNameField}-{fileNumber}.jpg"
33
34
# rename() function will
35
# rename all the files
36
os.rename(src, dst)
37
38
39
40
main()
41
42
43