Search code examples
pythonsortingfile-rename

Python Script to sort and rename files - Removes duplicates


I've written a small script that I needed to rename and sort files in the same folder where the script is. It renames the files into integers (1, 2, 3, 4, ...) based on the last modification of files:

import os
import sys
def gtime(nam):
    return os.path.getmtime('./'+nam)
files = os.listdir('.')
files.remove(str(sys.argv[0])[2:])
files = sorted(files, key=gtime)
for fi in range(len(files)):
    os.rename('./'+files[fi], './'+str(fi+1))

That was the best I've come up with to do so... The problem is when there's a duplicate (e.g. a file already named 1, maybe from a previous sort) it just removes it.. How can I prevent this from happening?? Is there any modification I can do to the code or a better alternative way???


Solution

  • You can't rename one file after the other, as you might overwrite already sorted files during the process. You can however use temporary names first and then rename the files to their final names in a second pass:

    import os
    import sys
    def gtime(nam):
        return os.path.getmtime('./'+nam)
    files = os.listdir('.')
    files.remove(str(sys.argv[0])[2:])
    files = sorted(files, key=gtime)
    for fi, file in enumerate(files):
        os.rename(file, str(fi+1)+".tmp")
    for fi in range(len(files)):
        os.rename(str(fi+1)+".tmp", str(fi+1))
    

    (untested)