simple renaming files program

Chris Rebert clp2 at rebertia.com
Mon Aug 9 15:55:26 EDT 2010


On Mon, Aug 9, 2010 at 3:19 AM, Peter Otten <__peter__ at web.de> wrote:
> 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.

Er, unless I'm really missing something, that's what my code already
does. Perhaps you misread it? The replace() clearly happens before the
2nd join(). I took special care to account for and avoid the potential
problem you're talking about.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list