[Tutor] Renaming Files in Directory

Peter Otten __peter__ at web.de
Thu Oct 9 11:36:18 CEST 2014


Felisha Lawrence wrote:

> I have the following program

>  import os
> 
> path = '/Users/felishalawrence/testswps/vol1'
> for file in os.listdir(path):
>         newFile = path+file[:file.rindex("v")]+"v20"
> 
>         print newFile

> and I want to output the results of the 'newFile' variable into the
> directory specified by the 'path' variable. There are current files in
> this directory, but I would like tho replace them with different names.
> Can anyone point me in the right direction?

So you can no longer defer that dreadful task? ;)

To rename a file you need its old and its new name, both preferrably with 
their complete path, for example

for old_name in os.listdir(path):
    old_file = os.path.join(path, old_name)

    new_name = old_name[:old_name.rindex("v")] + "v20"
    new_file = os.path.join(path, new_name)

    os.rename(old_file, new_file)

If there are only files containing a "v" in your 
/Users/felishalawrence/testswps/vol1 folder 
the above should already work. Here are a few ideas to make it more robust 
(or rather less brittle):

Verify that old_name contains a "v" using the `in` operator
Verify that old_file is a file using os.path.isfile()
Verify that new_file doesn't exist with os.path.exists()



More information about the Tutor mailing list