simple renaming files program

Peter Otten __peter__ at
Mon Aug 9 12:19:19 CEST 2010

Chris Rebert wrote:

> Hence (untested):
> from os import listdir, rename
> from os.path import isdir, join
> directory = raw_input("input file directory")
> s = raw_input("search for name")
> r = raw_input("replace name")
> for filename in listdir(directory):
>     path = join(directory, filename) #paste the directory name on
>     if isdir(path): continue #skip subdirectories (they're not files)
>     newname = filename.replace(s, r)
>     newpath = join(directory, newname)
>     n = rename(path, newpath)
>     print n

Warning: I don't remember how Windows handles this, but unix will happily
perform os.rename("alpha/alpha.txt", "beta/beta.txt") and overwrite 
beta/beta.txt with alpha/alpha.txt.

I'd rather modify the filename before joining it with the directory.

newname = filename.replace(s, r)
if newname != filename:
    path = os.path.join(directory, filename)
    newpath = os.path.join(directory, newname)
    os.rename(path, newpath)

If you don't you run the risk of operating in unexpected directories.


More information about the Python-list mailing list