Python to search text file string and replace it

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • DannyMc
    New Member
    • Aug 2007
    • 20

    Python to search text file string and replace it

    Hi ,

    i am in the middle of creating the script to match the string and replace it

    in mount.txt
    mickey:/work1 /work1 bla bla bla
    mickey:/work2 /work2 bla bla bla
    micket:/job /job bla bla bla


    Code:
    #!/usr/bin/python
    import string
    s = open("/usr2/py/mount.txt","r+")
    for line in s.readlines():
       print line
       string.replace(line, 'mickey','minnie')
       print line
    s.close()
    However, the string.replace seems not working, any advice??? Thank you!

    I am using CentOS 4.6 and the python is 2.3.4
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Hello DannyMc,

    string.replace( ) does not modify the argument string in place, but returns a modified string. You must make an assignment. Unless your file is very large, I would suggest updating the text in the file by reading the file, modifying the text, and writing the modified text back to the file. You can use string method replace() instead of importing the string module.
    Code:
    s = open("mount.txt").read()
    s = s.replace('mickey', 'minnie')
    f = open("mount.txt", 'w')
    f.write(s)
    f.close()

    Comment

    • DannyMc
      New Member
      • Aug 2007
      • 20

      #3
      thanks for the solution bvdet!!

      Comment

      • ghostdog74
        Recognized Expert Contributor
        • Apr 2006
        • 511

        #4
        you can use fileinput for inplace editing
        Code:
        import fileinput
        for line in fileinput.FileInput("file", inplace=1):
            line=line.replace("old","new")
            print line

        Comment

        • DannyMc
          New Member
          • Aug 2007
          • 20

          #5
          Hi guys, i managed to solve my problem with the following scripts:

          Code:
          #!/usr/bin/python
          import re
          #fstab location, use w mode as need to overwrite whole file.
          s = open("/usr2/py/mount.txt","r")
          #temp txt file to store new mount.
          tmpfile = open("/usr2/py/tmp.txt","a")
          #new nas mount point
          newmount = open("/usr2/py/newmount.txt","r")
          #search pg-swnas1 line
          for line in s.readlines():
              if re.search("filer", line, re.IGNORECASE) != None:
                  print line
              else:
                  tmpfile.write(line)
          #read the latest mount point
          readmount = newmount.read()
          #append to temp file
          tmpfile.write(readmount)
          s.close()
          tmpfile.close()
          tmpfile = open("/usr2/py/tmp.txt","r")
          readtmp = tmpfile.read()
          s = open("/usr2/py/mount.txt","w")
          s.write(readtmp)
          
          tmpfile.close()
          newmount.close()
          Though the code works, but it seems not a clean code. Is there anyway to simplify it???

          Comment

          • bvdet
            Recognized Expert Specialist
            • Oct 2006
            • 2851

            #6
            I am a bit unclear about what mount.txt and newmount.txt contain and what you need to replace. You do not need re. You can test for membership with the in operator. If I understand correctly, this should work (untested):
            Code:
            mountList = open("/usr2/py/mount.txt", "r").readlines()
            newmountList = open("/usr2/py/newmount.txt","r").readlines()
            outputList = [item for item in mountList if "filer" not in item.lower()]
            outputList.extend(newmountList)
            f = open("/usr2/py/mount.txt","w")
            f.write(''.join(outputList))
            f.close()

            Comment

            • sarrae1406
              New Member
              • Aug 2017
              • 1

              #7
              Works nice, thanks !

              Comment

              • Mrityunj2018
                New Member
                • Nov 2018
                • 1

                #8
                hi bvdet,

                The script works fine for single file but how can i replace for multiple files in a directory .

                could you write the script please .
                My file extensions are .xlf
                folder c:/mrit/

                with kind regards,
                MJ

                Comment

                Working...