#!/usr/bin/env python3 import os import sys def reduce_string(string, min_len): versions = [] for i in range(min_len, len(string) + 1): versions.append(string[:i]) versions.reverse() return versions def maximum_common_string(listofstrings, min_len): '''compare items of a list, grouping by common strings, keeping groups as small as possible''' for filepath in listofstrings: base = os.path.splitext(os.path.basename(filepath))[0] string_versions = reduce_string(base, min_len) for string in string_versions: common_strings = [x for x in listofstrings if string in x] if len(common_strings) > 2: return (string, common_strings) return def safe_move(files, directory): if not os.path.exists(directory): os.makedirs(directory) for item in files: newPath = os.path.join(directory, item) if not os.path.exists(newPath): currentPath = os.path.join(os.path.dirname(directory), item) print(f"moving {os.path.join(os.path.dirname(directory), item)} to {os.path.join(directory, item)}") os.rename(currentPath, newPath) else: print("file exists, skipping") return def main(): if len(sys.argv) > 1: workingPath = os.path.abspath(sys.argv[1]) else: print("need directory") sys.exit() filepaths = os.listdir(workingPath) while strings := maximum_common_string(filepaths, 6): for x in strings[1]: filepaths.pop(filepaths.index(x)) safe_move(strings[1], os.path.join(workingPath, strings[0])) return if __name__ == "__main__": main()