[Tutor] Renaming Files in Directory

Alan Gauld alan.gauld at btinternet.com
Thu Oct 9 13:02:34 CEST 2014


On 09/10/14 00:58, Felisha Lawrence wrote:
> Hello,
> 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.

You want the os.rename function.

Also you should use os.path.join() to create the path rather than string 
addition. It will ensure the correct separators are used
for the OS.

You might also want to look at glob.glob() rather than listdir
to get a listing of files matching a wildcard pattern.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list