FW: [Tutor] Changing filenames

John Choi johnc@greatentertaining.com
Mon, 10 Apr 2000 16:42:25 -0700

I'm trying this out on a text file on a mapped network drive but get a....

SyntaxError: can't assign to literal

What does this mean?

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
John Choi
Sent: Monday, April 10, 2000 4:20 PM
To: Python Tutor Mailing List
Subject: FW: [Tutor] Changing filenames


The file naming convention goes like this...
filename.YYYYMMDD, where the extension is the date when the file was saved.
This file is saved everyday (you guessed it, web log file).

> 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! :)

| Michael P. Reilly, Release Engineer | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |

Tutor maillist  -  Tutor@python.org