String find and replace

Geoff Gerrietts geoff at gerrietts.net
Tue Aug 26 19:34:58 EDT 2003


Quoting hokieghal99 (hokiegal99 at hotmail.com):
> import os, string
> print " "
> setpath = raw_input("Enter the path: ")
> def find_replace(setpath):
>    for root, dirs, files in os.walk(setpath):
>       fname = files
>       for fname in files:
>          find = string.find(file(os.path.join(root,fname), 'rb').read(), 'THIS')
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                              this string is never bound to a name
                              (ie, you never assign str=file(...).read())
>          print find
>          if find >=1:
>              replace = string.replace(str, 'THIS', 'THAT')
                                        ^^^
                                     this name is currently bound to
                                     the builtin function str()

> find_replace(setpath)
> print " "


You might consider the fragment below, instead. It's a couple lines
longer, but safer (your .close() happens exactly when you want it to)
and probably more readable.

   for root, dirs, files in os.walk(setpath):
      fname = files
      for fname in files:
         myfile = file(os.path.join(root,fname), 'rb')
         mystr = myfile.read()
         myfile.close()
         find = string.find(mystr, 'THIS')
         print find
         if find >=1:
             replace = string.replace(mystr, 'THIS', 'THAT')


Luck,
--G.

-- 
Geoff Gerrietts          "information 'wants' to be free in the same way nature
<geoff at gerrietts.net>         'abhors' a vacuum: it's not some moral view, it's
http://www.gerrietts.net/            just the natural state of affairs." -- jwz





More information about the Python-list mailing list