Script Discussion & Critique

Peter Otten __peter__ at web.de
Thu Aug 28 05:03:04 EDT 2003


hokiegal99 wrote:

> Thanks for any ideas, pointers or critique... most of the ideas behind
> the script came from the list.

Choose variable names that make their intended purpose clear, e.g.
searchToken/replaceToken instead of x/y.

> search = string.find(data, x)
>     if search >=1:

This is wrong as others have already explained. I recommend:

if searchToken in data:
   # perform replacement

(I did it with .find() till yesterday, but no more! I like that Python
minimizes the need of artificial indices:-)

Factor out reusable code, e.g:

def replaceTokenInTree(rootFolder, searchToken, replaceToken,
filterFunc=None)
def replaceTokenInFile(filename, searchToken, replaceToken, backupFile=None)

This will pay off as your scripts grow (or your script grows:-), so make it
a habit as soon as possible.


Some observations that are not directly code-related:

You can change - and possibly corrupt - *many* files in one run of you
script. So you might add a confirmation prompt repeating searchToken,
replaceToken and the root directory (resolved to an absolute path) and -
somewhat more ambitious - a means to generate backups.

When replacement fails on one file, e. g. due to access rights, you could
catch the exception and prompt the user, if he wants to continue or abort
the script.

Chances are that there are some files in the tree that you do not want to
process, so you should add some basic filtering. The fnmatch module might
be helpful.


Last but most important:

Take time to build a test file tree, and include all special cases you can
think of (including those you consider irrelevant) e. g. files
starting/ending with search token, zerolength file, file with readonly
access.

Peter




More information about the Python-list mailing list