#!/usr/bin/env python ''' bl_rename.py - Given a series of paired-end read filenames, replace the leftmost common string with a specified string. Synopsis: bl_rename.py target newname file [file]... For each file whose name contains with target, create a symbolic link to target whose name contains newname EXAMPLE Given the following files in the current working directory: testfile1.text testfile2.text testfile3.text testfile4.text bl_rename.py text txt * changes the names to testfile1.txt testfile2.txt testfile3.txt testfile4.txt bl_rename.py ile '' * changes the names to testf1.txt testf2.txt testf3.txt testf4.txt @modified: January 5, 2019 @author: Brian Fristensky @contact: Brian.Fristensky@umanitoba.ca ''' """ optparse is deprecated in favor of argparse as of Python 2.7. However, since 2.7 is not always present on many systems, at this writing, it is safer to stick with optparse for now. It should be easy to change later, since the syntax is very similar between argparse and optparse. from optparse import OptionParser """ from optparse import OptionParser import os import re import stat import subprocess import sys PROGRAM = "bl_rename.py : " USAGE = "\n\tUSAGE: bl_rename.py target [newname]" DEBUG = False if DEBUG : print('bl_rename.py: Debugging mode on') # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - class Parameters: """ Wrapper class for command line parameters """ def __init__(self): """ Initializes arguments: TARGET = "" NEWNAME = "" FILES = [] Then calls read_args() to fill in their values from command line """ self.TARGET = "" self.NEWNAME = "" self.FILES = [] self.read_args() if DEBUG : print('------------ Parameters from command line ------') print(' TARGET: ' + self.TARGET) print(' NEWNAME: ' + self.NEWNAME) print(' FILES: ' + str(self.FILES)) print() def read_args(self): """ Read command line arguments into a Parameter object """ self.TARGET = sys.argv[1] self.NEWNAME = sys.argv[2] if len(sys.argv) > 3 : self.FILES = sys.argv[3:] # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def ReName(TARGET,NEWNAME,FILES) : for FN in FILES : if os.path.isfile(FN) : NewFN = FN.replace(TARGET,NEWNAME) os.rename(FN,NewFN) #======================== MAIN PROCEDURE ========================== def main(): """ Called when not in documentation mode. """ # Read parameters from command line P = Parameters() ReName(P.TARGET,P.NEWNAME,P.FILES) if __name__ == "__main__": main() #else: #used to generate documentation # import doctest # doctest.testmod() #if (BM.documentor() or "-test" in sys.argv): # pass #else: # main()