PDA

View Full Version : Batch renaming


kiwipenguin
11-07-2002, 04:50 AM
Me again. You guys are a fantastic source of knowledge so I figured I'd ask again. I have a directory with 46 jpg files that I want to batch rename. I figured this was a job for Python.



import os
path = raw_input("Path to files: ")
files = os.listdir(path)
for file in files:
newname = "Holiday" + file
os.rename(file, newname)
print "Renamed", file, "to", newname


print "Done"



Yet my code dies at the os.rename line with: OSError: [Errno 2] No such file or directory

But when I comment it out, everything appears fine. Could someone point out the blindly obvious that I'm missing? 8)

nex
11-07-2002, 07:14 AM
os.chdir(path)

should fix it :)

jemfinch
11-07-2002, 09:21 AM
I'd just use a simple bash script on the command line to do this, though.


cd theDirectory
for file in *.jpg do
mv $file Holiday$file
done


If you don't like that, you should (if you want a good learning challenge) try to generalize your program to take, say, a regex on the command line with which to both recognize which files needed modification and what modification to make.

find theDirectory | changeName.py "s/(.*\.jpg)/Holiday\1/"

Or something similarly general.

Jeremy