simple renaming files program
Dave Angel
davea at ieee.org
Mon Aug 9 10:07:36 EDT 2010
blur959 wrote:
> On Aug 9, 6:01 pm, Chris Rebert <c... at rebertia.com> wrote:
>
>> <snip>
>> os.rename() takes paths that are absolute (or possibly relative to the
>> cwd), not paths that are relative to some arbitrary directory (as
>> returned by os.listdir()).
>> Also, never name a variable "file"; it shadows the name of the built-in type.
>>
>> Hence (untested):
>> from os import listdir, rename
>> from os.path import isdir, join
>> directory =aw_input("input file directory")
>> s =aw_input("search for name")
>> r =aw_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
>>
>> Cheers,
>> Chris
>> --http://blog.rebertia.com
>>
>
> Thanks, they worked!
>
>
A refinement: use os.path.join(), rather than just join(). It's
smarter about adding the right kind of slash between the nodes, if
needed. Currently, if you leave off the trailing slash (from
"directory"), you'll end up with the files being one level up, and the
individual files having a string prepended.
DaveA
More information about the Python-list
mailing list