def run(self): r = stringutil.u(self.args.regex) s = stringutil.u(self.args.sub) if self.args.recursive: for dirpath, dirs, filenames in os.walk(self.args.dir): for fname in filenames: self.process_file(r, s, dirpath, fname) else: filenames = os.listdir(self.args.dir) for fname in filenames: self.process_file(r, s, self.args.dir, fname) n = len(self.filenames_map) sn = len(str(n)) for i, (k, v) in enumerate(self.filenames_map.iteritems()): print(u"%*d. %s => %s" % (sn, i + 1, k, v)) if consoleutil.confirm("Do you want to do the rename?"): for i, (k, v) in enumerate(self.filenames_map.iteritems()): print("%*d. Rename %s to %s" % (sn, i + 1, k, v)) os.rename(k, v) return 0 else: print("Aborted") return 1
def process_file(self, regex, sub, dirpath, filename): filename = stringutil.u(filename) m = re.match(regex, filename, re.UNICODE) if m: old = os.path.abspath(os.path.join(dirpath, filename)) groups = (m.group(0),) + m.groups() new = os.path.abspath( os.path.join( dirpath, sub.format(*groups), ) ) self.filenames_map[old] = new