Fmira75
Fmira75

Reputation: 25

How to organize images within a folder by mtime using python

I'm a beginner at python who has been trying to write a script that moves images, renames them and then organizes them by mtime. At the moment I've achieved the first two steps, but I have no clue how to organize images by time within a folder. So far, I've been able to organize the names of the images by mtime and then print them using this code:

    import os

    path = os.path.join('C:\\', 'Users', 'Francisco', 'Desktop', 'Archive2')

    def sorted_ls(path):
        mtime = lambda f: os.stat(os.path.join(path, f)).st_mtime
        return list(sorted(os.listdir(path), key=mtime))

    print(sorted_ls(path))

However, I want to make it so that the script actually reorganizes the images in 'Archive2' by mtime, not just print out a list of the images already organized. Any help would be very much appreciated, thanks!

Upvotes: 1

Views: 52

Answers (1)

yabk
yabk

Reputation: 140

If I got it correctly, you want to change the names of files so that when you organize them by name they are organized by mtime as well.

You already achieved in getting them sorted by mtime, only thing that is left to do is to iterate through the list and rename the files.

To do that you can use this code:

l = sorted_ls(path)
location = 'C:/Users/Francisco/Desktop/Archive2/'
for i in range(len(l)):
    os.rename(location+l[i], location+'file'+str(i).zfill(4))

str.fill fills up higher digits with zeros if the number is too small.

Upvotes: 1

Related Questions