#!/usr/bin/env python
#
# Change the extension of input files
#
import sys
import os

help = """
David Edwards  <david@300m.us> Mon Jul 2, 2012
Python 3 script

change_ext - Change the extension of file argument 2-n using argument
one as the new extension.

Usage:  change_ext ext file(s)

where
          ext    Replace existing file extensions with this one

     "file(s)"   One or more file names that can contain wild cards.

If there is no extension, then the new one is appended.

This works on subdirectory names as well as regular files.

File extensions are always converted to lower case. Dot files are
not treated as an extension.

Example:  change_ext jpg *.jpeg

  God Rules.jpeg  -->  God Rules.jpg
  picture         -->  picture.jpg

BUGS: Does not work for things like this: change_ext jpg ~/photo.dir/pic
"""

if len(sys.argv) < 2:
	print(help)
	exit(1)			# See: http://docs.python.org/py3k/library/sys.html#sys.exit

# Process the command line arguments
ext = sys.argv[1]

for name in sys.argv[2:]:
	if os.path.exists(name):
		#new = eval(actions[opt])
		j = name.rfind('.')

		if j < 0:
			new = name + '.' + ext
		elif j != 0:
			new = name[:j+1] + ext
		else:
			continue

		if os.path.exists(new):
			print('"' + name + '" not renamed. "' + new + '" already exists.')
		else:
			print(name + ' --> ' + new)
			os.rename(name, new)
	else:
		print("File not found: " + name)

