[Tutor] File renaming using os.rename problem (spir)

Sander Sweers sander.sweers at gmail.com
Wed Dec 9 00:50:15 CET 2009

On Tue, 2009-12-08 at 14:55 -0800, Roy Hinkelman wrote:
> shutil.copy2(_files_to_mod + "\\" + fname, _files_to_mod + "\\" +
> new_name)

You can make os.path.join sort out the directory seprator for you. It
will add a / under linux and \ under windows.

>>> os.path.join('Testing dir','oldname dir','filename')
'Testing dir/oldname dir/filename'

So the code above can be like,
import os
oldname = os.path.join(_files_to_mod, fname)
newname = os.path.join(_files_to_mod, new_name)
shutil.copy2(oldname, newname)

Not sure if it is a concern in your case but as far as I know
shutil.copy2 will overwrite any existing files with the new_name without

Have a look at [1] for a great explanation on os.path.


[1] http://blog.doughellmann.com/2008/01/pymotw-ospath.html

More information about the Tutor mailing list