Replacing a string in a text file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • afshin
    New Member
    • May 2012
    • 4

    Replacing a string in a text file

    Hello Python Experts

    I have a text file containing a code (written for a software)

    I need to write a code in Python, to first, read the text file, search for a string, change that string with something else and save the file.

    Let's say that the file name is test.txt which is in D:\ry directory, and I need to change E=100 to E=200 in this file.

    I should mention that I am a beginner in python.

    Thansk
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    It could be as simple as this:
    Code:
    >>> s = open("test12.txt").read()
    >>> f = open("test13.txt", 'w')
    >>> f.write(s.replace("E=100", "E=200"))
    >>> f.close()
    >>>

    Comment

    • afshin
      New Member
      • May 2012
      • 4

      #3
      Thanks. From you code, I wrote it like this:

      s = open("D:\test.t xt").read()
      f = open("D:\test1. txt", 'w')
      f.write(s.repla ce("E=100", "E=200"))
      f.close()

      But it gives me the following error:

      Traceback (most recent call last):
      File "D:\test2.p y", line 7, in <module>
      s = open("D:\test.t xt").read()
      IOError: [Errno 22] invalid mode ('r') or filename: 'D:\test.txt'

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        If you use a backslash character in the file name, it's a good idea to always escape it as in "D:\\test.t xt". Otherwise you could use the forward slash character "/". FYI - "\t" is interpreted as a tab character. "\\t" is interpreted as a backslash and t.

        Comment

        • afshin
          New Member
          • May 2012
          • 4

          #5
          Thank you very much. As I am learning it, I will back to you with new questions soon ;)

          Comment

          Working...