How can I organize files by looking at last digits of the file names in python?

165 Views Asked by At

I have a folder containing the file names something like below.

1asdf0001.png

2asdf0002.png

3asdf0003.png

4asdf0004.png

5asdf0005.png

6asdf0001.png

7asdf0002.png

8asdf0003.png

9asdf0004.png

10asdf0001.png

11asdf0002.png

.

.

.

Now, I want to make folders based on the last digit of the files.

folder 1: 1asdf0001.png, 2asdf0002.png, 3asdf0003.png, 4asdf0004.png, 5asdf0005.png

folder 2: 6asdf0001.png, 7asdf0002.png, 8asdf0003.png, 9asdf0004.png

folder 3: 10asdf0001.png, 11asdf0002.png

How can I do that in python? I was thinking to use "endswith" but I don't know how to set the random number.. Please help me.

1

There are 1 best solutions below

0
YOLO On

Here's a way to do:

from itertools import groupby

l = ["1asdf0001.png","2asdf0002.png","3asdf0003.png","4asdf0004.png","5asdf0005.png","6asdf0001.png",
     "7asdf0002.png","8asdf0003.png","9asdf0004.png","10asdf0001.png","11asdf0002.png"]

grps = {}
for en, (key, grp) in enumerate(groupby(l, key=lambda x: int(x[0]) // 6)):
    grps['folder' + str(en)] = [x for x in grp]

print(grps)

{'folder0': ['1asdf0001.png', '2asdf0002.png', '3asdf0003.png', '4asdf0004.png', '5asdf0005.png'], 
 'folder1': ['6asdf0001.png', '7asdf0002.png', '8asdf0003.png', '9asdf0004.png'], 
 'folder2': ['10asdf0001.png', '11asdf0002.png']}