Skip to content
Advertisement

How to rename files chronologically without changing their order?

I made an application in Python (link for source code at the bottom) which renames files (in a directory) by sorting them (based on their extension) into one of these: Image, Video, Text, GIF, Audio and Unknown Extension.

Basically, it loops through a directory, gets all the files in it, sorts them, for each file in the sorted list it assigns a value of its index in list and then renames the file. But, for some reason, it gives the same number twice or misses some in between.

So, I would like to rename them in chronological order, without changing the order in which they appear. For example, the third file before the process should be the same as the third file after the process and so on. like this:

Goal

I don’t know how to put my thoughts into Python’s code. But I think you can do it like this:

  1. Get all the files in a folder (Chronologically).
  2. If they contain a specific word (like Image or video), add them to the list named after the word it contains.
  3. Get the length(or count) of the list.
  4. In a for loop, split the file name by ' ' (Space). Check if the RHS of the name corresponds to the current value of loop, if it doesn’t rename it with the same name but this new value.

Minimal code to copy this error:

JavaScript

Advertisement

Answer

Assumed (from the image in the question) that there is a unique format of basename per file extension: format .jpg -> name format Image D where D is a digit(s). Those which do not satisfy the format are treated (and recorded) as exceptions and no actions is performed on them. For more complex situations a regex approach is suggested.

Idea: group by file extensions, sort each group, set new name, rename

Note

  • as first run maybe comment the line with os.rename
  • it has been tested only in current directory

Here a possible approach:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement