[Tutor] Changing filenames
Michael P. Reilly
arcege@shore.net
Mon, 10 Apr 2000 18:09:19 -0400 (EDT)
>
> I'd like to change all the filenames in a directory. They have a standard
> naming convention, but the important stuff is being used as a file type
> extension. Does anyone know of a way to append the existing extension to
> the end of the filename and then switch all the extensions to ".this"?
> -- John C.
>
You might want to clarify what "standard naming convention" is.
Standard for Windows is not a standard for Mac or UNIX.
I assume that you are asking how to append ".this" to the end of all
names of files in a directory.
>>> import os
>>> for fname in os.listdir(os.curdir): # files in current directory
... os.rename(fname, fname + '.this')
...
>>>
This gets you filenames like "spam.txt.this" and "eggs.spam.this".
If you want to do something more complex, for example, changing each
extension to be a part of the base name instead of the extension, e.g.
changing ".txt" to "-txt". Here you might get instead "spam-txt.this"
and "eggs-spam.this".
>>> import os
>>> for fname in os.listdir(os.curdir):
... basename, ext = os.path.splitext(fname)
... newname = basename + '-' + ext[1:] # chop off '.'
... os.rename(fname, newname + '.this')
...
>>>
Most of the tools in the os.path module will help you with what you
need. <URL: http://www.python.org/doc/current/lib/module-os.path.html>
Enjoy! :)
-Arcege
--
------------------------------------------------------------------------
| Michael P. Reilly, Release Engineer | Email: arcege@shore.net |
| Salem, Mass. USA 01970 | |
------------------------------------------------------------------------