Thanks for the help. I have attached a changed version that I believe is better.

I will join the python group... I didn't know it existed :).

Bob Miller wrote:
Martin Kelly wrote:

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 :).

That's basically the right approach.  Three comments.

First, change this...
        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

to this...
        newfile = file.replace(word , r_word)
        if file != newfile:
            os.rename(os.path.join(root, file), os.path.join(root, newfile))
            print file, "renamed to", newfile

Why?  (a) less work for the extremely common case, (b) rename
will update the file's inode-changed time.

Second, instead of using os.getcwd() as your default topdir, you can
use '.', which always resolves to the current directory.  Also,
instead of prepending root to each path, you can chdir to the topdir
and use relative paths from there.

        if len(sys.argv[1:]) == 3:
            top, word, r_word = sys.argv[1:]
            os.chdir(sys.argv[1])
        elif len(sys.argv[1:]) == 2:
            word, r_word = sys.argv[1:]
        else:
            usage()

and...
        for root, dir, files in os.walk('.'):

That'll change your progress message text.

Third, and most important, if you're teaching yourself Python, why not
join EUGLUG's Python mailing list?  It's much lower volume than the
mailing list, and it's all about Python.

http://www.euglug.org/mailman/listinfo/python


--
-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)

def checkargs():
	if len(sys.argv[1:]) == 2: # If directory not given, default to current directory
		topdir = "."
		new_word = sys.argv[1]
		r_new_word = sys.argv[2]
	elif len(sys.argv[1:]) < 2: # There should always be at least 2 arguments
		usage()
	else:
		topdir = sys.argv[1]
		new_word = sys.argv[2]
		r_new_word = sys.argv[3]

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

	return topdir, new_word, r_new_word

topdir, new_word, r_new_word = checkargs()
os.chdir(topdir)

for root, dir, files in os.walk(topdir):
	for file in files:
		new_file = file.replace(new_word , r_new_word)
		if file != new_file:
			os.rename(file,new_file)
			print	file, "renamed to", new_file + "."
_______________________________________________
EUGLUG mailing list
euglug@euglug.org
http://www.euglug.org/mailman/listinfo/euglug

Reply via email to