snippets

More or less useful code snippets
Log | Files | Refs

BRenamer.py (1177B)


      1 #!/bin/python
      2 
      3 # Bulk renamer, currently in a pretty specific format.
      4 # Continue building on this to make a general bulk renamer
      5 
      6 import sys
      7 import os
      8 import re
      9 from subprocess import call
     10 
     11 cwd = os.getcwd()
     12 filelist = os.listdir(cwd)
     13 filelist.sort()
     14 if len(sys.argv) > 2:
     15     regout = sys.argv[2]
     16     regin = sys.argv[1]
     17 else:
     18     regin = input("Enter regex for input files: ")
     19     regout = input("Enter common part for output files: ")
     20     # () is replaced with the unique part
     21 
     22 rin = re.compile(regin)
     23 
     24 matches     = []
     25 new_names   = []
     26 for filename in filelist:
     27     match = rin.search(filename)
     28     if match:
     29 # Group 1 contains unique part of original file_name.
     30 # Place this correctly in the new filename:
     31         print(match.group(1))
     32         new_nm = regout.replace("{}", match.group(1))
     33         matches.append(filename)
     34         new_names.append(new_nm)
     35 
     36 for i in range(len(new_names)):
     37     print("\t{}   ->   {}".format(matches[i], new_names[i]))
     38 
     39 reprompt = input("\nRename the above files? [y/n]: ")
     40 if reprompt == 'y':
     41     print("renamin'")
     42     for i in range(len(new_names)):
     43         call(["mv","{}/{}".format(cwd, matches[i]),"{}/{}".format(cwd, new_names[i])])
     44 
     45