Sequentially rename batch files with Python by sorting them according to their creation time

Viewed 108

I need to sequentially rename batch files by sorting them according to their creation date and time. The first name should be started from 1001 and it should be increase by 1. To do this I have got a sample code from https://www.geeksforgeeks.org/rename-multiple-files-using-python

It renames filenames randomly. But I need to do it according to file creation date and time. How can I do it?

If anyone suggest VBScript or PowerShell it will be also highly appreciated.

import os


def main():
    folder = "xyz"
    for count, filename in enumerate(os.listdir(folder)):
        dst = f"1001{str(count)}.jpg"
        src = f"{folder}/{filename}"  # foldername/filename, if .jpg file is outside folder
        dst = f"{folder}/{dst}"

        os.rename(src, dst)


# Driver Code
if __name__ == '__main__':
    main()

Advance thanks for your help.

Best regards

1 Answers

you can use os.path.getctime() to get the creation time and sort accordingly.

Here is an example snippet that works:

import os

def main():
    folder = "xyz"

    files = os.listdir(folder)
    files.sort(key=lambda x: os.path.getctime(f"{folder}/{x}"))

    for count, filename in enumerate(files):
        dst = f"{1001 + count}.jpg"
        src = f"{folder}/{filename}"  # foldername/filename, if .jpg file is outside folder
        dst = f"{folder}/{dst}"

        os.rename(src, dst)


# Driver Code
if __name__ == '__main__':
    main()

You may substitute os.path.getctime with os.path.getmtime() to sort by last modification time instead.

Related