I have a folder containing .png
images that are named image1.png, image2.png, image3.png
etc.
The way this folder is organized, 3 consecutive images represent data from the same subject, so I'd like them to be named with the same identifying number + a letter to differentiate them. Like this:
image1.png --> 1-a.png
image2.png --> 1-b.png
image3.png --> 1-c.png
image4.png --> 2-a.png
image5.png --> 2-b.png
image6.png --> 2-c.png
and so on.
What would be the best way to do this? a Perl
script? or generating a .txt
in python
with the desired names and then using it to rename the files? I'm using Ubuntu
.
Thanks in advance!
Given a file list files
in Python, you can use itertools.product
to generate your desired pairings of numbers and letters:
from itertools import product
import os
os.chdir(directory_containing_images)
# instead of hard-coding files you will actually want:
# files = os.listdir('.')
files = ['image1.png', 'image2.png', 'image3.png', 'image4.png', 'image5.png', 'image6.png']
for file, (n, a) in zip(files, product(range(1, len(files) // 3 + 2), 'abc')):
os.rename(file, '{}-{}.png'.format(n, a))
If you replace os.rename
with print
, the above code will output:
image1.png 1-a.png
image2.png 1-b.png
image3.png 1-c.png
image4.png 2-a.png
image5.png 2-b.png
image6.png 2-c.png