Hi, I was creating a python script to rename all files in a directory as specified by a given pattern. I know there are already programs that can do this, but I am doing this as a learning exercise.

The format for the command is like this:
rename /home foo bar
... to change everything in /home with "foo" in it to "bar"

I got it working, but it's rather messy, and I was wondering if there's a more elegant way to do it; after all, it is python :).

The .py file is attached.

Thanks all.

--
-Martin
#!/usr/bin/python

import os
import sys

def usage():
	print	"Usage:"
	print	"To replace all of \"foo\" with \"bar\" in /home:"
	print	"rename /home foo bar"
	sys.exit(2)

if len(sys.argv[1:]) == 2: # If topectory not given, default to current topectory
	top = os.getcwd()
	word = sys.argv[1]
	r_word = sys.argv[2]
elif len(sys.argv[1:]) < 2: # There should always be at least 2 arguments
	usage()
else:
	top = sys.argv[1]
	word = sys.argv[2]
	r_word = sys.argv[3]

if not os.path.exists(top):
	print	"No such file or topectory or insufficent permissons:", top
	sys.exit(2)

for root, dir, files in os.walk(top):
	for file in files:
		newfile = file.replace(word , r_word)
		os.rename(os.path.join(root, file), os.path.join(root, newfile))
		if file != newfile:
			print	file, "renamed to", newfile
_______________________________________________
EUGLUG mailing list
[email protected]
http://www.euglug.org/mailman/listinfo/euglug

Reply via email to