Kjetil's Information Center: A Blog About My Projects

Rename by Reference

Another specialized tool for a specialized task, this Python script renames files in a directory based on names from another directory. The pattern matching is only based on matching substrings. If a filename fits as a substring within another filename from the reference directory, then that reference filename is selected as a possible choice. Filename extensions are excluded automatically.

Take a look:

#!/usr/bin/python

import os
import glob

def rename_by_reference(target_dir, ref_dir):
    ref = dict()
    for f in glob.glob(os.path.join(ref_dir, "*")):
        if os.path.isdir(f):
            (name, ext) = (os.path.basename(f), "")
        else:
            (name, ext) = os.path.splitext(os.path.basename(f))
        ref[name] = ext

    for f in glob.glob(os.path.join(target_dir, "*")):
        if os.path.isdir(f):
            (name, ext) = (os.path.basename(f), "")
        else:
            (name, ext) = os.path.splitext(os.path.basename(f))
        for (ref_name, ref_ext) in ref.iteritems():
            if name == ref_name:
                continue # Equal, not interesting...
            if name in ref_name:
                print name + ext, "--->", ref_name + ext
                answer = raw_input("Rename? ").lower()
                if answer.startswith("q"):
                    return
                elif answer.startswith("y"):
                    src = f
                    dst = os.path.join(os.path.dirname(f), ref_name + ext)
                    os.rename(src, dst)
                    break

if __name__ == "__main__":
    import sys

    if len(sys.argv) < 3:
        print "Usage: %s <target dir> <reference dir>" % (sys.argv[0])
        sys.exit(1)

    rename_by_reference(sys.argv[1], sys.argv[2])
    sys.exit(0)
          


Topic: Scripts and Code, by Kjetil @ 09/10-2016, Article Link