String find and replace

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • hokieghal99

    String find and replace

    import os, string
    print " "
    setpath = raw_input("Ente r the path: ")
    def find_replace(se tpath):
    for root, dirs, files in os.walk(setpath ):
    fname = files
    for fname in files:
    find = string.find(fil e(os.path.join( root,fname),
    'rb').read(), 'THIS')
    print find
    if find >=1:
    replace = string.replace( str, 'THIS', 'THAT')
    find_replace(se tpath)
    print " "

    Why doesn't this work? I get this error:

    Traceback (most recent call last):
    File "html_find_repl ace.py", line 12, in ?
    find_replace(se tpath)
    File "html_find_repl ace.py", line 11, in find_replace
    replace = string.replace( str, 'THIS', 'THAT')
    File "/usr/local/lib/python2.3/string.py", line 370, in replace
    return s.replace(old, new, maxsplit)
    TypeError: expected a character buffer object

  • John Roth

    #2
    Re: String find and replace


    "hokieghal9 9" <hokiegal99@hot mail.com> wrote in message
    news:bigq2u$p23 $1@solaris.cc.v t.edu...[color=blue]
    > import os, string
    > print " "
    > setpath = raw_input("Ente r the path: ")
    > def find_replace(se tpath):
    > for root, dirs, files in os.walk(setpath ):
    > fname = files
    > for fname in files:
    > find = string.find(fil e(os.path.join( root,fname),
    > 'rb').read(), 'THIS')
    > print find
    > if find >=1:
    > replace = string.replace( str, 'THIS', 'THAT')
    > find_replace(se tpath)
    > print " "
    >
    > Why doesn't this work? I get this error:
    >
    > Traceback (most recent call last):
    > File "html_find_repl ace.py", line 12, in ?
    > find_replace(se tpath)
    > File "html_find_repl ace.py", line 11, in find_replace
    > replace = string.replace( str, 'THIS', 'THAT')
    > File "/usr/local/lib/python2.3/string.py", line 370, in replace
    > return s.replace(old, new, maxsplit)
    > TypeError: expected a character buffer object[/color]

    what's "str" in line 11?

    John Roth[color=blue]
    >[/color]


    Comment

    • Gerhard Häring

      #3
      Re: String find and replace

      hokieghal99 wrote:[color=blue]
      > import os, string
      > print " "
      > setpath = raw_input("Ente r the path: ")
      > def find_replace(se tpath):
      > for root, dirs, files in os.walk(setpath ):
      > fname = files
      > for fname in files:
      > find = string.find(fil e(os.path.join( root,fname), 'rb').read(),
      > 'THIS')
      > print find
      > if find >=1:
      > replace = string.replace( str, 'THIS', 'THAT')[/color]
      ^^^

      In your app, what do you think 'str' is?

      You haven't defined it, but it still exists. It's the string type, *not*
      a particular string (cos you haven't defined it). That's why you get the
      error below:
      [color=blue]
      > find_replace(se tpath)
      > print " "
      >
      > Why doesn't this work? I get this error:
      >
      > Traceback (most recent call last):
      > File "html_find_repl ace.py", line 12, in ?
      > find_replace(se tpath)
      > File "html_find_repl ace.py", line 11, in find_replace
      > replace = string.replace( str, 'THIS', 'THAT')
      > File "/usr/local/lib/python2.3/string.py", line 370, in replace
      > return s.replace(old, new, maxsplit)
      > TypeError: expected a character buffer object[/color]

      -- Gerhard

      Comment

      • hokiegal99

        #4
        Re: String find and replace

        Thanks for the explanation, I can make it work this way:

        import os, string
        setpath = raw_input("Ente r the path: ")
        for root, dirs, files in os.walk(setpath ):
        fname = files
        x = 'THIS'
        y = 'THAT'
        for fname in files:
        myfile = file(os.path.jo in(root,fname), 'r')
        mystr = myfile.read()
        myfile.close()
        search = string.find(mys tr, 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.

        Thanks Everyone!!!



        Geoff Gerrietts wrote:[color=blue]
        > Quoting hokieghal99 (hokiegal99@hot mail.com):
        >[color=green]
        >>import os, string
        >>print " "
        >>setpath = raw_input("Ente r the path: ")
        >>def find_replace(se tpath):
        >> for root, dirs, files in os.walk(setpath ):
        >> fname = files
        >> for fname in files:
        >> find = string.find(fil e(os.path.join( root,fname), 'rb').read(), 'THIS')[/color]
        >
        > ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^
        > this string is never bound to a name
        > (ie, you never assign str=file(...).r ead())
        >[color=green]
        >> print find
        >> if find >=1:
        >> replace = string.replace( str, 'THIS', 'THAT')[/color]
        >
        > ^^^
        > this name is currently bound to
        > the builtin function str()
        >
        >[color=green]
        >>find_replace( setpath)
        >>print " "[/color]
        >
        >
        >
        > 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.jo in(root,fname), 'rb')
        > mystr = myfile.read()
        > myfile.close()
        > find = string.find(mys tr, 'THIS')
        > print find
        > if find >=1:
        > replace = string.replace( mystr, 'THIS', 'THAT')
        >
        >
        > Luck,
        > --G.
        >[/color]


        Comment

        • John Roth

          #5
          Re: String find and replace


          "hokiegal99 " <hokiegal99@vt. edu> wrote in message
          news:3F4C04F8.5 070401@vt.edu.. .[color=blue]
          > Thanks for the explanation, I can make it work this way:
          >
          > import os, string
          > setpath = raw_input("Ente r the path: ")
          > for root, dirs, files in os.walk(setpath ):
          > fname = files
          > x = 'THIS'
          > y = 'THAT'
          > for fname in files:
          > myfile = file(os.path.jo in(root,fname), 'r')
          > mystr = myfile.read()
          > myfile.close()
          > search = string.find(mys tr, 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.[/color]

          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[color=blue]
          >
          > Thanks Everyone!!!
          >
          >
          >
          > Geoff Gerrietts wrote:[color=green]
          > > Quoting hokieghal99 (hokiegal99@hot mail.com):
          > >[color=darkred]
          > >>import os, string
          > >>print " "
          > >>setpath = raw_input("Ente r the path: ")
          > >>def find_replace(se tpath):
          > >> for root, dirs, files in os.walk(setpath ):
          > >> fname = files
          > >> for fname in files:
          > >> find = string.find(fil e(os.path.join( root,fname), 'rb').read(),[/color][/color][/color]
          'THIS')[color=blue][color=green]
          > >
          > >[/color][/color]
          ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^[color=blue][color=green]
          > > this string is never bound to a name
          > > (ie, you never assign[/color][/color]
          str=file(...).r ead())[color=blue][color=green]
          > >[color=darkred]
          > >> print find
          > >> if find >=1:
          > >> replace = string.replace( str, 'THIS', 'THAT')[/color]
          > >
          > > ^^^
          > > this name is currently bound to
          > > the builtin function str()
          > >
          > >[color=darkred]
          > >>find_replace( setpath)
          > >>print " "[/color]
          > >
          > >
          > >
          > > 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.jo in(root,fname), 'rb')
          > > mystr = myfile.read()
          > > myfile.close()
          > > find = string.find(mys tr, 'THIS')
          > > print find
          > > if find >=1:
          > > replace = string.replace( mystr, 'THIS', 'THAT')
          > >
          > >
          > > Luck,
          > > --G.
          > >[/color]
          >
          >[/color]


          Comment

          • hokiegal99

            #6
            Re: String find and replace

            John Roth wrote:[color=blue]
            > 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[/color]

            No, I'm trying to find 'this' in files and replace it with 'that'
            recursively through a directory. It works, but it doesn't actually
            commit the change to the files, it finds 'this' and reports that it
            replaced it with 'that', but when I run the scipt again it reports the
            same files that it just fixed.

            Comment

            • John Roth

              #7
              Re: String find and replace


              "hokiegal99 " <hokiegal99@hot mail.com> wrote in message
              news:3F4C0CC4.2 0400@hotmail.co m...[color=blue]
              > John Roth wrote:[color=green]
              > > 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[/color]
              >
              > No, I'm trying to find 'this' in files and replace it with 'that'
              > recursively through a directory. It works, but it doesn't actually
              > commit the change to the files, it finds 'this' and reports that it
              > replaced it with 'that', but when I run the scipt again it reports the
              > same files that it just fixed.[/color]

              Oh. You need to open it again for write and write the
              changed string back out. The string doesn't have any
              persistant connection to the file.

              John Roth[color=blue]
              >[/color]


              Comment

              • Erik Max Francis

                #8
                Re: String find and replace

                hokiegal99 wrote:
                [color=blue]
                > I hate to answer my own post, but I think I understand what I'm doing
                > wrong. I'm finding and replacing 'this' with 'that' in the varible
                > named
                > mystr, not the actual files. So, how would I go about making the
                > change
                > to the actual files instead of a variable that contains their content?[/color]

                Easy:

                inputFile = file(filename, 'r')
                data = inputFile.read( )
                inputFile.close ()
                data = data.replace(th is, that)
                outputFile = file(filename, 'w')
                outputFile.writ e(data)
                outputFile.clos e()

                --
                Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
                __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
                / \ There never was a good war or a bad peace.
                \__/ Benjamin Franklin

                Comment

                • hokiegal99

                  #9
                  Re: String find and replace

                  Easy for you maybe ;)

                  That works great. I learn something each time I post to the list. With a
                  community like this, Python will be around forever!!! Thanks for the help.

                  Erik Max Francis wrote:[color=blue]
                  > hokiegal99 wrote:
                  >
                  >[color=green]
                  >>I hate to answer my own post, but I think I understand what I'm doing
                  >>wrong. I'm finding and replacing 'this' with 'that' in the varible
                  >>named
                  >>mystr, not the actual files. So, how would I go about making the
                  >>change
                  >>to the actual files instead of a variable that contains their content?[/color]
                  >
                  >
                  > Easy:
                  >
                  > inputFile = file(filename, 'r')
                  > data = inputFile.read( )
                  > inputFile.close ()
                  > data = data.replace(th is, that)
                  > outputFile = file(filename, 'w')
                  > outputFile.writ e(data)
                  > outputFile.clos e()[/color]


                  Comment

                  • Thomas Güttler

                    #10
                    Re: String find and replace

                    hokiegal99 wrote:
                    [color=blue]
                    > Thanks for the explanation, I can make it work this way:
                    >
                    > import os, string
                    > setpath = raw_input("Ente r the path: ")
                    > for root, dirs, files in os.walk(setpath ):
                    > fname = files
                    > x = 'THIS'
                    > y = 'THAT'
                    > for fname in files:
                    > myfile = file(os.path.jo in(root,fname), 'r')
                    > mystr = myfile.read()
                    > myfile.close()
                    > search = string.find(mys tr, 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.[/color]

                    I once wrote a replace recursive script. Maybe it helps you:


                    thomas




                    Comment

                    • hokiegal99

                      #11
                      Re: String find and replace

                      Thomas Güttler wrote:[color=blue]
                      > I once wrote a replace recursive script. Maybe it helps you:
                      > http://www.thomas-guettler.de/script...cursive.py.txt
                      >
                      > thomas[/color]

                      Yes that's very helpful, but a bit too complex for me at this point in
                      time. Here is the script that I put together from all of the responses I
                      recieved from the list:

                      #Thanks to comp.lang.pytho n
                      import os, string
                      print " "
                      print "************** *************** *************** **********"
                      print " Three Easy Steps to a Recursive find and Replace "
                      print "************** *************** *************** **********"
                      print " "
                      x = raw_input("1. Enter the string that you'd like to find: ")
                      print " "
                      y = raw_input("2. What would you like to replace %s with: " %x)
                      print " "
                      setpath = raw_input("3. Enter the path where the prgroam should run: ")
                      print " "
                      for root, dirs, files in os.walk(setpath ):
                      fname = files
                      for fname in files:
                      inputFile = file(os.path.jo in(root,fname), 'r')
                      data = inputFile.read( )
                      inputFile.close ()
                      search = string.find(dat a, x)
                      if search >=1:
                      data = data.replace(x, y)
                      outputFile = file(os.path.jo in(root,fname), 'w')
                      outputFile.writ e(data)
                      outputFile.clos e()
                      print "Replacing" , x, "with", y, "in", fname
                      print " "
                      print "********** "
                      print " Done "
                      print "********** "
                      print " "

                      Comment

                      Working...