String find and replace

John Roth newsgroups at jhrothjr.com
Wed Aug 27 03:26:10 CEST 2003


"hokiegal99" <hokiegal99 at vt.edu> wrote in message
news:3F4C04F8.5070401 at vt.edu...
> Thanks for the explanation, I can make it work this way:
>
> import os, string
> setpath = raw_input("Enter the path: ")
> for root, dirs, files in os.walk(setpath):
>     fname = files
>     x = 'THIS'
>     y = 'THAT'
>     for fname in files:
>        myfile = file(os.path.join(root,fname), 'r')
>        mystr = myfile.read()
>        myfile.close()
>        search = string.find(mystr, x)
>        if search >=1:
>           string.replace(mystr, x, y)
>           print "Replacing", x, "with", y, "in", fname
>
> If only I could actually make the change to the files! It works in
> theory, but not in practice ;) Anyone recommend how to actual write the
> change to the file? I'm new to this, so be kind.

Are you trying to rename the file? Look under os - Files and Directories
for the rename() function. It's 6.1.4 in the 2.2.3 docs.

John Roth
>
> Thanks Everyone!!!
>
>
>
> Geoff Gerrietts wrote:
> > 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.
> >
>
>






More information about the Python-list mailing list