1111
1212import os
1313import sys
14-
14+ import argparse
1515
1616def batch_rename (work_dir , old_ext , new_ext ):
1717 '''
@@ -24,25 +24,38 @@ def batch_rename(work_dir, old_ext, new_ext):
2424 file_ext = os .path .splitext (filename )[1 ]
2525 # Start of the logic to check the file extensions, if old_ext = file_ext
2626 if old_ext == file_ext :
27- # Set newfile to be the filename, replaced with the new extension
28- newfile = filename .replace (old_ext , new_ext )
27+ # Returns changed name of the file with new extention
28+ name_list = list (filename )
29+ name_list [len (name_list )- len (old_ext ):]= list (new_ext )
30+ newfile = '' .join (name_list )
31+
2932 # Write the files
3033 os .rename (
3134 os .path .join (work_dir , filename ),
3235 os .path .join (work_dir , newfile )
3336 )
3437
38+ def get_parser ():
39+ parser = argparse .ArgumentParser (description = 'change extension of files in a working directory' )
40+ parser .add_argument ('work_dir' , metavar = 'WORK_DIR' , type = str , nargs = 1 , help = 'the directory where to change extension' )
41+ parser .add_argument ('old_ext' , metavar = 'OLD_EXT' , type = str , nargs = 1 , help = 'old extension' )
42+ parser .add_argument ('new_ext' , metavar = 'NEW_EXT' , type = str , nargs = 1 , help = 'new extension' )
43+ return parser
3544
3645def main ():
3746 '''
3847 This will be called if the script is directly invoked.
3948 '''
49+ # adding command line argument
50+ parser = get_parser ()
51+ args = vars (parser .parse_args ())
52+
4053 # Set the variable work_dir with the first argument passed
41- work_dir = sys . argv [ 1 ]
54+ work_dir = args [ 'work_dir' ][ 0 ]
4255 # Set the variable old_ext with the second argument passed
43- old_ext = sys . argv [ 2 ]
56+ old_ext = args [ 'old_ext' ][ 0 ]
4457 # Set the variable new_ext with the third argument passed
45- new_ext = sys . argv [ 3 ]
58+ new_ext = args [ 'new_ext' ][ 0 ]
4659
4760 batch_rename (work_dir , old_ext , new_ext )
4861
0 commit comments