import os from os import curdir from os.path import abspath, relpath import sys def topath(fn): return relpath(abspath(fn), start=abspath(curdir)) with open("filters.txt") as inp: data = inp.readlines() filters = {} for line in data: line = line.strip() if line.startswith('#'): destination = line[1:].strip() os.makedirs(destination, exist_ok=True) elif line: filter_term = line.lower() filters[filter_term] = topath(destination.lower()) filter_folders = set(filters.values()) for root, dirs, files in os.walk('.'): if root == '.': continue root = topath(root) if root.lower() in filter_folders: continue for fn in files: test_fn = fn.lower() for ft in filters: if ft not in test_fn: continue dest = filters[ft] os.rename(os.path.join(root, fn), os.path.join(dest, fn)) break